@cardstack/boxel-cli 0.2.0-unstable.294 → 0.2.0-unstable.298

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,111 +1,111 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Hc=Object.create;var mi=Object.defineProperty;var Wc=Object.getOwnPropertyDescriptor;var Bc=Object.getOwnPropertyNames;var Yc=Object.getPrototypeOf,Xc=Object.prototype.hasOwnProperty;var g=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var zc=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Bc(e))!Xc.call(r,i)&&i!==t&&mi(r,i,{get:()=>e[i],enumerable:!(n=Wc(e,i))||n.enumerable});return r};var O=(r,e,t)=>(t=r!=null?Hc(Yc(r)):{},zc(e||!r||!r.__esModule?mi(t,"default",{value:r,enumerable:!0}):t,r));var di=g((Xw,Jc)=>{Jc.exports={name:"dotenv",version:"16.6.1",description:"Loads environment variables from .env file",main:"lib/main.js",types:"lib/main.d.ts",exports:{".":{types:"./lib/main.d.ts",require:"./lib/main.js",default:"./lib/main.js"},"./config":"./config.js","./config.js":"./config.js","./lib/env-options":"./lib/env-options.js","./lib/env-options.js":"./lib/env-options.js","./lib/cli-options":"./lib/cli-options.js","./lib/cli-options.js":"./lib/cli-options.js","./package.json":"./package.json"},scripts:{"dts-check":"tsc --project tests/types/tsconfig.json",lint:"standard",pretest:"npm run lint && npm run dts-check",test:"tap run --allow-empty-coverage --disable-coverage --timeout=60000","test:coverage":"tap run --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov",prerelease:"npm test",release:"standard-version"},repository:{type:"git",url:"git://github.com/motdotla/dotenv.git"},homepage:"https://github.com/motdotla/dotenv#readme",funding:"https://dotenvx.com",keywords:["dotenv","env",".env","environment","variables","config","settings"],readmeFilename:"README.md",license:"BSD-2-Clause",devDependencies:{"@types/node":"^18.11.3",decache:"^4.6.2",sinon:"^14.0.1",standard:"^17.0.0","standard-version":"^9.5.0",tap:"^19.2.0",typescript:"^4.8.4"},engines:{node:">=12"},browser:{fs:!1}}});var wi=g((zw,pe)=>{var dr=require("fs"),dt=require("path"),Kc=require("os"),Qc=require("crypto"),Zc=di(),pr=Zc.version,eu=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function tu(r){let e={},t=r.toString();t=t.replace(/\r\n?/mg,`
2
+ "use strict";var Hc=Object.create;var mi=Object.defineProperty;var Wc=Object.getOwnPropertyDescriptor;var Bc=Object.getOwnPropertyNames;var Yc=Object.getPrototypeOf,Xc=Object.prototype.hasOwnProperty;var y=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var zc=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Bc(e))!Xc.call(r,i)&&i!==t&&mi(r,i,{get:()=>e[i],enumerable:!(n=Wc(e,i))||n.enumerable});return r};var O=(r,e,t)=>(t=r!=null?Hc(Yc(r)):{},zc(e||!r||!r.__esModule?mi(t,"default",{value:r,enumerable:!0}):t,r));var di=y((Xw,Jc)=>{Jc.exports={name:"dotenv",version:"16.6.1",description:"Loads environment variables from .env file",main:"lib/main.js",types:"lib/main.d.ts",exports:{".":{types:"./lib/main.d.ts",require:"./lib/main.js",default:"./lib/main.js"},"./config":"./config.js","./config.js":"./config.js","./lib/env-options":"./lib/env-options.js","./lib/env-options.js":"./lib/env-options.js","./lib/cli-options":"./lib/cli-options.js","./lib/cli-options.js":"./lib/cli-options.js","./package.json":"./package.json"},scripts:{"dts-check":"tsc --project tests/types/tsconfig.json",lint:"standard",pretest:"npm run lint && npm run dts-check",test:"tap run --allow-empty-coverage --disable-coverage --timeout=60000","test:coverage":"tap run --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov",prerelease:"npm test",release:"standard-version"},repository:{type:"git",url:"git://github.com/motdotla/dotenv.git"},homepage:"https://github.com/motdotla/dotenv#readme",funding:"https://dotenvx.com",keywords:["dotenv","env",".env","environment","variables","config","settings"],readmeFilename:"README.md",license:"BSD-2-Clause",devDependencies:{"@types/node":"^18.11.3",decache:"^4.6.2",sinon:"^14.0.1",standard:"^17.0.0","standard-version":"^9.5.0",tap:"^19.2.0",typescript:"^4.8.4"},engines:{node:">=12"},browser:{fs:!1}}});var wi=y((zw,he)=>{var pr=require("fs"),mt=require("path"),Kc=require("os"),Qc=require("crypto"),Zc=di(),hr=Zc.version,eu=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function tu(r){let e={},t=r.toString();t=t.replace(/\r\n?/mg,`
3
3
  `);let n;for(;(n=eu.exec(t))!=null;){let i=n[1],o=n[2]||"";o=o.trim();let s=o[0];o=o.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),s==='"'&&(o=o.replace(/\\n/g,`
4
- `),o=o.replace(/\\r/g,"\r")),e[i]=o}return e}function ru(r){r=r||{};let e=yi(r);r.path=e;let t=j.configDotenv(r);if(!t.parsed){let s=new Error(`MISSING_DATA: Cannot parse ${e} for an unknown reason`);throw s.code="MISSING_DATA",s}let n=gi(r).split(","),i=n.length,o;for(let s=0;s<i;s++)try{let a=n[s].trim(),l=iu(t,a);o=j.decrypt(l.ciphertext,l.key);break}catch(a){if(s+1>=i)throw a}return j.parse(o)}function nu(r){console.log(`[dotenv@${pr}][WARN] ${r}`)}function He(r){console.log(`[dotenv@${pr}][DEBUG] ${r}`)}function hi(r){console.log(`[dotenv@${pr}] ${r}`)}function gi(r){return r&&r.DOTENV_KEY&&r.DOTENV_KEY.length>0?r.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function iu(r,e){let t;try{t=new URL(e)}catch(a){if(a.code==="ERR_INVALID_URL"){let l=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw l.code="INVALID_DOTENV_KEY",l}throw a}let n=t.password;if(!n){let a=new Error("INVALID_DOTENV_KEY: Missing key part");throw a.code="INVALID_DOTENV_KEY",a}let i=t.searchParams.get("environment");if(!i){let a=new Error("INVALID_DOTENV_KEY: Missing environment part");throw a.code="INVALID_DOTENV_KEY",a}let o=`DOTENV_VAULT_${i.toUpperCase()}`,s=r.parsed[o];if(!s){let a=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${o} in your .env.vault file.`);throw a.code="NOT_FOUND_DOTENV_ENVIRONMENT",a}return{ciphertext:s,key:n}}function yi(r){let e=null;if(r&&r.path&&r.path.length>0)if(Array.isArray(r.path))for(let t of r.path)dr.existsSync(t)&&(e=t.endsWith(".vault")?t:`${t}.vault`);else e=r.path.endsWith(".vault")?r.path:`${r.path}.vault`;else e=dt.resolve(process.cwd(),".env.vault");return dr.existsSync(e)?e:null}function pi(r){return r[0]==="~"?dt.join(Kc.homedir(),r.slice(1)):r}function ou(r){let e=!!(r&&r.debug),t=r&&"quiet"in r?r.quiet:!0;(e||!t)&&hi("Loading env from encrypted .env.vault");let n=j._parseVault(r),i=process.env;return r&&r.processEnv!=null&&(i=r.processEnv),j.populate(i,n,r),{parsed:n}}function su(r){let e=dt.resolve(process.cwd(),".env"),t="utf8",n=!!(r&&r.debug),i=r&&"quiet"in r?r.quiet:!0;r&&r.encoding?t=r.encoding:n&&He("No encoding is specified. UTF-8 is used by default");let o=[e];if(r&&r.path)if(!Array.isArray(r.path))o=[pi(r.path)];else{o=[];for(let u of r.path)o.push(pi(u))}let s,a={};for(let u of o)try{let c=j.parse(dr.readFileSync(u,{encoding:t}));j.populate(a,c,r)}catch(c){n&&He(`Failed to load ${u} ${c.message}`),s=c}let l=process.env;if(r&&r.processEnv!=null&&(l=r.processEnv),j.populate(l,a,r),n||!i){let u=Object.keys(a).length,c=[];for(let m of o)try{let d=dt.relative(process.cwd(),m);c.push(d)}catch(d){n&&He(`Failed to load ${m} ${d.message}`),s=d}hi(`injecting env (${u}) from ${c.join(",")}`)}return s?{parsed:a,error:s}:{parsed:a}}function au(r){if(gi(r).length===0)return j.configDotenv(r);let e=yi(r);return e?j._configVault(r):(nu(`You set DOTENV_KEY but you are missing a .env.vault file at ${e}. Did you forget to build it?`),j.configDotenv(r))}function lu(r,e){let t=Buffer.from(e.slice(-64),"hex"),n=Buffer.from(r,"base64"),i=n.subarray(0,12),o=n.subarray(-16);n=n.subarray(12,-16);try{let s=Qc.createDecipheriv("aes-256-gcm",t,i);return s.setAuthTag(o),`${s.update(n)}${s.final()}`}catch(s){let a=s instanceof RangeError,l=s.message==="Invalid key length",u=s.message==="Unsupported state or unable to authenticate data";if(a||l){let c=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw c.code="INVALID_DOTENV_KEY",c}else if(u){let c=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw c.code="DECRYPTION_FAILED",c}else throw s}}function cu(r,e,t={}){let n=!!(t&&t.debug),i=!!(t&&t.override);if(typeof e!="object"){let o=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw o.code="OBJECT_REQUIRED",o}for(let o of Object.keys(e))Object.prototype.hasOwnProperty.call(r,o)?(i===!0&&(r[o]=e[o]),n&&He(i===!0?`"${o}" is already defined and WAS overwritten`:`"${o}" is already defined and was NOT overwritten`)):r[o]=e[o]}var j={configDotenv:su,_configVault:ou,_parseVault:ru,config:au,decrypt:lu,parse:tu,populate:cu};pe.exports.configDotenv=j.configDotenv;pe.exports._configVault=j._configVault;pe.exports._parseVault=j._parseVault;pe.exports.config=j.config;pe.exports.decrypt=j.decrypt;pe.exports.parse=j.parse;pe.exports.populate=j.populate;pe.exports=j});var $i=g((Jw,Ei)=>{var xe={};process.env.DOTENV_CONFIG_ENCODING!=null&&(xe.encoding=process.env.DOTENV_CONFIG_ENCODING);process.env.DOTENV_CONFIG_PATH!=null&&(xe.path=process.env.DOTENV_CONFIG_PATH);process.env.DOTENV_CONFIG_QUIET!=null&&(xe.quiet=process.env.DOTENV_CONFIG_QUIET);process.env.DOTENV_CONFIG_DEBUG!=null&&(xe.debug=process.env.DOTENV_CONFIG_DEBUG);process.env.DOTENV_CONFIG_OVERRIDE!=null&&(xe.override=process.env.DOTENV_CONFIG_OVERRIDE);process.env.DOTENV_CONFIG_DOTENV_KEY!=null&&(xe.DOTENV_KEY=process.env.DOTENV_CONFIG_DOTENV_KEY);Ei.exports=xe});var Ri=g((Kw,bi)=>{var uu=/^dotenv_config_(encoding|path|quiet|debug|override|DOTENV_KEY)=(.+)$/;bi.exports=function(e){let t=e.reduce(function(n,i){let o=i.match(uu);return o&&(n[o[1]]=o[2]),n},{});return"quiet"in t||(t.quiet="true"),t}});var We=g(gr=>{var pt=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},hr=class extends pt{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};gr.CommanderError=pt;gr.InvalidArgumentError=hr});var ht=g(wr=>{var{InvalidArgumentError:fu}=We(),yr=class{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new fu(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function mu(r){let e=r.name()+(r.variadic===!0?"...":"");return r.required?"<"+e+">":"["+e+"]"}wr.Argument=yr;wr.humanReadableArgName=mu});var br=g($r=>{var{humanReadableArgName:du}=ht(),Er=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter(i=>!i._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((i,o)=>i.name().localeCompare(o.name())),t}compareOptions(e,t){let n=i=>i.short?i.short.replace(/^-/,""):i.long.replace(/^--/,"");return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(i=>!i.hidden),n=e._getHelpOption();if(n&&!n.hidden){let i=n.short&&e._findOption(n.short),o=n.long&&e._findOption(n.long);!i&&!o?t.push(n):n.long&&!o?t.push(e.createOption(n.long,n.description)):n.short&&!i&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let i=n.options.filter(o=>!o.hidden);t.push(...i)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(n=>du(n)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((n,i)=>Math.max(n,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(i)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((n,i)=>Math.max(n,this.displayWidth(t.styleOptionTerm(t.optionTerm(i)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((n,i)=>Math.max(n,this.displayWidth(t.styleOptionTerm(t.optionTerm(i)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((n,i)=>Math.max(n,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(i)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let n="";for(let i=e.parent;i;i=i.parent)n=i.name()+" "+n;return n+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatHelp(e,t){let n=t.padWidth(e,t),i=t.helpWidth??80;function o(m,d){return t.formatItem(m,n,d,t)}let s=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],a=t.commandDescription(e);a.length>0&&(s=s.concat([t.boxWrap(t.styleCommandDescription(a),i),""]));let l=t.visibleArguments(e).map(m=>o(t.styleArgumentTerm(t.argumentTerm(m)),t.styleArgumentDescription(t.argumentDescription(m))));l.length>0&&(s=s.concat([t.styleTitle("Arguments:"),...l,""]));let u=t.visibleOptions(e).map(m=>o(t.styleOptionTerm(t.optionTerm(m)),t.styleOptionDescription(t.optionDescription(m))));if(u.length>0&&(s=s.concat([t.styleTitle("Options:"),...u,""])),t.showGlobalOptions){let m=t.visibleGlobalOptions(e).map(d=>o(t.styleOptionTerm(t.optionTerm(d)),t.styleOptionDescription(t.optionDescription(d))));m.length>0&&(s=s.concat([t.styleTitle("Global Options:"),...m,""]))}let c=t.visibleCommands(e).map(m=>o(t.styleSubcommandTerm(t.subcommandTerm(m)),t.styleSubcommandDescription(t.subcommandDescription(m))));return c.length>0&&(s=s.concat([t.styleTitle("Commands:"),...c,""])),s.join(`
4
+ `),o=o.replace(/\\r/g,"\r")),e[i]=o}return e}function ru(r){r=r||{};let e=yi(r);r.path=e;let t=j.configDotenv(r);if(!t.parsed){let s=new Error(`MISSING_DATA: Cannot parse ${e} for an unknown reason`);throw s.code="MISSING_DATA",s}let n=gi(r).split(","),i=n.length,o;for(let s=0;s<i;s++)try{let a=n[s].trim(),l=iu(t,a);o=j.decrypt(l.ciphertext,l.key);break}catch(a){if(s+1>=i)throw a}return j.parse(o)}function nu(r){console.log(`[dotenv@${hr}][WARN] ${r}`)}function We(r){console.log(`[dotenv@${hr}][DEBUG] ${r}`)}function hi(r){console.log(`[dotenv@${hr}] ${r}`)}function gi(r){return r&&r.DOTENV_KEY&&r.DOTENV_KEY.length>0?r.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function iu(r,e){let t;try{t=new URL(e)}catch(a){if(a.code==="ERR_INVALID_URL"){let l=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw l.code="INVALID_DOTENV_KEY",l}throw a}let n=t.password;if(!n){let a=new Error("INVALID_DOTENV_KEY: Missing key part");throw a.code="INVALID_DOTENV_KEY",a}let i=t.searchParams.get("environment");if(!i){let a=new Error("INVALID_DOTENV_KEY: Missing environment part");throw a.code="INVALID_DOTENV_KEY",a}let o=`DOTENV_VAULT_${i.toUpperCase()}`,s=r.parsed[o];if(!s){let a=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${o} in your .env.vault file.`);throw a.code="NOT_FOUND_DOTENV_ENVIRONMENT",a}return{ciphertext:s,key:n}}function yi(r){let e=null;if(r&&r.path&&r.path.length>0)if(Array.isArray(r.path))for(let t of r.path)pr.existsSync(t)&&(e=t.endsWith(".vault")?t:`${t}.vault`);else e=r.path.endsWith(".vault")?r.path:`${r.path}.vault`;else e=mt.resolve(process.cwd(),".env.vault");return pr.existsSync(e)?e:null}function pi(r){return r[0]==="~"?mt.join(Kc.homedir(),r.slice(1)):r}function ou(r){let e=!!(r&&r.debug),t=r&&"quiet"in r?r.quiet:!0;(e||!t)&&hi("Loading env from encrypted .env.vault");let n=j._parseVault(r),i=process.env;return r&&r.processEnv!=null&&(i=r.processEnv),j.populate(i,n,r),{parsed:n}}function su(r){let e=mt.resolve(process.cwd(),".env"),t="utf8",n=!!(r&&r.debug),i=r&&"quiet"in r?r.quiet:!0;r&&r.encoding?t=r.encoding:n&&We("No encoding is specified. UTF-8 is used by default");let o=[e];if(r&&r.path)if(!Array.isArray(r.path))o=[pi(r.path)];else{o=[];for(let u of r.path)o.push(pi(u))}let s,a={};for(let u of o)try{let c=j.parse(pr.readFileSync(u,{encoding:t}));j.populate(a,c,r)}catch(c){n&&We(`Failed to load ${u} ${c.message}`),s=c}let l=process.env;if(r&&r.processEnv!=null&&(l=r.processEnv),j.populate(l,a,r),n||!i){let u=Object.keys(a).length,c=[];for(let m of o)try{let d=mt.relative(process.cwd(),m);c.push(d)}catch(d){n&&We(`Failed to load ${m} ${d.message}`),s=d}hi(`injecting env (${u}) from ${c.join(",")}`)}return s?{parsed:a,error:s}:{parsed:a}}function au(r){if(gi(r).length===0)return j.configDotenv(r);let e=yi(r);return e?j._configVault(r):(nu(`You set DOTENV_KEY but you are missing a .env.vault file at ${e}. Did you forget to build it?`),j.configDotenv(r))}function lu(r,e){let t=Buffer.from(e.slice(-64),"hex"),n=Buffer.from(r,"base64"),i=n.subarray(0,12),o=n.subarray(-16);n=n.subarray(12,-16);try{let s=Qc.createDecipheriv("aes-256-gcm",t,i);return s.setAuthTag(o),`${s.update(n)}${s.final()}`}catch(s){let a=s instanceof RangeError,l=s.message==="Invalid key length",u=s.message==="Unsupported state or unable to authenticate data";if(a||l){let c=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw c.code="INVALID_DOTENV_KEY",c}else if(u){let c=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw c.code="DECRYPTION_FAILED",c}else throw s}}function cu(r,e,t={}){let n=!!(t&&t.debug),i=!!(t&&t.override);if(typeof e!="object"){let o=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw o.code="OBJECT_REQUIRED",o}for(let o of Object.keys(e))Object.prototype.hasOwnProperty.call(r,o)?(i===!0&&(r[o]=e[o]),n&&We(i===!0?`"${o}" is already defined and WAS overwritten`:`"${o}" is already defined and was NOT overwritten`)):r[o]=e[o]}var j={configDotenv:su,_configVault:ou,_parseVault:ru,config:au,decrypt:lu,parse:tu,populate:cu};he.exports.configDotenv=j.configDotenv;he.exports._configVault=j._configVault;he.exports._parseVault=j._parseVault;he.exports.config=j.config;he.exports.decrypt=j.decrypt;he.exports.parse=j.parse;he.exports.populate=j.populate;he.exports=j});var $i=y((Jw,Ei)=>{var _e={};process.env.DOTENV_CONFIG_ENCODING!=null&&(_e.encoding=process.env.DOTENV_CONFIG_ENCODING);process.env.DOTENV_CONFIG_PATH!=null&&(_e.path=process.env.DOTENV_CONFIG_PATH);process.env.DOTENV_CONFIG_QUIET!=null&&(_e.quiet=process.env.DOTENV_CONFIG_QUIET);process.env.DOTENV_CONFIG_DEBUG!=null&&(_e.debug=process.env.DOTENV_CONFIG_DEBUG);process.env.DOTENV_CONFIG_OVERRIDE!=null&&(_e.override=process.env.DOTENV_CONFIG_OVERRIDE);process.env.DOTENV_CONFIG_DOTENV_KEY!=null&&(_e.DOTENV_KEY=process.env.DOTENV_CONFIG_DOTENV_KEY);Ei.exports=_e});var Ri=y((Kw,bi)=>{var uu=/^dotenv_config_(encoding|path|quiet|debug|override|DOTENV_KEY)=(.+)$/;bi.exports=function(e){let t=e.reduce(function(n,i){let o=i.match(uu);return o&&(n[o[1]]=o[2]),n},{});return"quiet"in t||(t.quiet="true"),t}});var Be=y(yr=>{var dt=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},gr=class extends dt{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};yr.CommanderError=dt;yr.InvalidArgumentError=gr});var pt=y(Er=>{var{InvalidArgumentError:fu}=Be(),wr=class{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new fu(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function mu(r){let e=r.name()+(r.variadic===!0?"...":"");return r.required?"<"+e+">":"["+e+"]"}Er.Argument=wr;Er.humanReadableArgName=mu});var Rr=y(br=>{var{humanReadableArgName:du}=pt(),$r=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter(i=>!i._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((i,o)=>i.name().localeCompare(o.name())),t}compareOptions(e,t){let n=i=>i.short?i.short.replace(/^-/,""):i.long.replace(/^--/,"");return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(i=>!i.hidden),n=e._getHelpOption();if(n&&!n.hidden){let i=n.short&&e._findOption(n.short),o=n.long&&e._findOption(n.long);!i&&!o?t.push(n):n.long&&!o?t.push(e.createOption(n.long,n.description)):n.short&&!i&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let i=n.options.filter(o=>!o.hidden);t.push(...i)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(n=>du(n)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((n,i)=>Math.max(n,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(i)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((n,i)=>Math.max(n,this.displayWidth(t.styleOptionTerm(t.optionTerm(i)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((n,i)=>Math.max(n,this.displayWidth(t.styleOptionTerm(t.optionTerm(i)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((n,i)=>Math.max(n,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(i)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let n="";for(let i=e.parent;i;i=i.parent)n=i.name()+" "+n;return n+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatHelp(e,t){let n=t.padWidth(e,t),i=t.helpWidth??80;function o(m,d){return t.formatItem(m,n,d,t)}let s=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],a=t.commandDescription(e);a.length>0&&(s=s.concat([t.boxWrap(t.styleCommandDescription(a),i),""]));let l=t.visibleArguments(e).map(m=>o(t.styleArgumentTerm(t.argumentTerm(m)),t.styleArgumentDescription(t.argumentDescription(m))));l.length>0&&(s=s.concat([t.styleTitle("Arguments:"),...l,""]));let u=t.visibleOptions(e).map(m=>o(t.styleOptionTerm(t.optionTerm(m)),t.styleOptionDescription(t.optionDescription(m))));if(u.length>0&&(s=s.concat([t.styleTitle("Options:"),...u,""])),t.showGlobalOptions){let m=t.visibleGlobalOptions(e).map(d=>o(t.styleOptionTerm(t.optionTerm(d)),t.styleOptionDescription(t.optionDescription(d))));m.length>0&&(s=s.concat([t.styleTitle("Global Options:"),...m,""]))}let c=t.visibleCommands(e).map(m=>o(t.styleSubcommandTerm(t.subcommandTerm(m)),t.styleSubcommandDescription(t.subcommandDescription(m))));return c.length>0&&(s=s.concat([t.styleTitle("Commands:"),...c,""])),s.join(`
5
5
  `)}displayWidth(e){return Si(e).length}styleTitle(e){return e}styleUsage(e){return e.split(" ").map(t=>t==="[options]"?this.styleOptionText(t):t==="[command]"?this.styleSubcommandText(t):t[0]==="["||t[0]==="<"?this.styleArgumentText(t):this.styleCommandText(t)).join(" ")}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(" ").map(t=>t==="[options]"?this.styleOptionText(t):t[0]==="["||t[0]==="<"?this.styleArgumentText(t):this.styleSubcommandText(t)).join(" ")}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,n,i){let s=" ".repeat(2);if(!n)return s+e;let a=e.padEnd(t+e.length-i.displayWidth(e)),l=2,c=(this.helpWidth??80)-t-l-2,m;return c<this.minWidthToWrap||i.preformatted(n)?m=n:m=i.boxWrap(n,c).replace(/\n/g,`
6
6
  `+" ".repeat(t+l)),s+a+" ".repeat(l)+m.replace(/\n/g,`
7
7
  ${s}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let n=e.split(/\r\n|\n/),i=/[\s]*[^\s]+/g,o=[];return n.forEach(s=>{let a=s.match(i);if(a===null){o.push("");return}let l=[a.shift()],u=this.displayWidth(l[0]);a.forEach(c=>{let m=this.displayWidth(c);if(u+m<=t){l.push(c),u+=m;return}o.push(l.join(""));let d=c.trimStart();l=[d],u=this.displayWidth(d)}),o.push(l.join(""))}),o.join(`
8
- `)}};function Si(r){let e=/\x1b\[\d*(;\d*)*m/g;return r.replace(e,"")}$r.Help=Er;$r.stripColor=Si});var xr=g(vr=>{var{InvalidArgumentError:pu}=We(),Rr=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=hu(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e=="string"&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new pu(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?vi(this.name().replace(/^no-/,"")):vi(this.name())}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Sr=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,n)=>{this.positiveOptions.has(n)&&this.dualOptions.add(n)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let i=this.negativeOptions.get(n).presetArg,o=i!==void 0?i:!1;return t.negate===(o===e)}};function vi(r){return r.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function hu(r){let e,t,n=/^-[^-]$/,i=/^--[^-]/,o=r.split(/[ |,]+/).concat("guard");if(n.test(o[0])&&(e=o.shift()),i.test(o[0])&&(t=o.shift()),!e&&n.test(o[0])&&(e=o.shift()),!e&&i.test(o[0])&&(e=t,t=o.shift()),o[0].startsWith("-")){let s=o[0],a=`option creation failed due to '${s}' in option flags '${r}'`;throw/^-[^-][^-]/.test(s)?new Error(`${a}
8
+ `)}};function Si(r){let e=/\x1b\[\d*(;\d*)*m/g;return r.replace(e,"")}br.Help=$r;br.stripColor=Si});var _r=y(xr=>{var{InvalidArgumentError:pu}=Be(),Sr=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=hu(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e=="string"&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new pu(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?vi(this.name().replace(/^no-/,"")):vi(this.name())}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},vr=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,n)=>{this.positiveOptions.has(n)&&this.dualOptions.add(n)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let i=this.negativeOptions.get(n).presetArg,o=i!==void 0?i:!1;return t.negate===(o===e)}};function vi(r){return r.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function hu(r){let e,t,n=/^-[^-]$/,i=/^--[^-]/,o=r.split(/[ |,]+/).concat("guard");if(n.test(o[0])&&(e=o.shift()),i.test(o[0])&&(t=o.shift()),!e&&n.test(o[0])&&(e=o.shift()),!e&&i.test(o[0])&&(e=t,t=o.shift()),o[0].startsWith("-")){let s=o[0],a=`option creation failed due to '${s}' in option flags '${r}'`;throw/^-[^-][^-]/.test(s)?new Error(`${a}
9
9
  - a short flag is a single dash and a single character
10
10
  - either use a single dash and a single character (for a short flag)
11
11
  - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):n.test(s)?new Error(`${a}
12
12
  - too many short flags`):i.test(s)?new Error(`${a}
13
13
  - too many long flags`):new Error(`${a}
14
- - unrecognised flag format`)}if(e===void 0&&t===void 0)throw new Error(`option creation failed due to no flags found in '${r}'.`);return{shortFlag:e,longFlag:t}}vr.Option=Rr;vr.DualOptions=Sr});var _i=g(xi=>{function gu(r,e){if(Math.abs(r.length-e.length)>3)return Math.max(r.length,e.length);let t=[];for(let n=0;n<=r.length;n++)t[n]=[n];for(let n=0;n<=e.length;n++)t[0][n]=n;for(let n=1;n<=e.length;n++)for(let i=1;i<=r.length;i++){let o=1;r[i-1]===e[n-1]?o=0:o=1,t[i][n]=Math.min(t[i-1][n]+1,t[i][n-1]+1,t[i-1][n-1]+o),i>1&&n>1&&r[i-1]===e[n-2]&&r[i-2]===e[n-1]&&(t[i][n]=Math.min(t[i][n],t[i-2][n-2]+1))}return t[r.length][e.length]}function yu(r,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=r.startsWith("--");t&&(r=r.slice(2),e=e.map(s=>s.slice(2)));let n=[],i=3,o=.4;return e.forEach(s=>{if(s.length<=1)return;let a=gu(r,s),l=Math.max(r.length,s.length);(l-a)/l>o&&(a<i?(i=a,n=[s]):a===i&&n.push(s))}),n.sort((s,a)=>s.localeCompare(a)),t&&(n=n.map(s=>`--${s}`)),n.length>1?`
14
+ - unrecognised flag format`)}if(e===void 0&&t===void 0)throw new Error(`option creation failed due to no flags found in '${r}'.`);return{shortFlag:e,longFlag:t}}xr.Option=Sr;xr.DualOptions=vr});var _i=y(xi=>{function gu(r,e){if(Math.abs(r.length-e.length)>3)return Math.max(r.length,e.length);let t=[];for(let n=0;n<=r.length;n++)t[n]=[n];for(let n=0;n<=e.length;n++)t[0][n]=n;for(let n=1;n<=e.length;n++)for(let i=1;i<=r.length;i++){let o=1;r[i-1]===e[n-1]?o=0:o=1,t[i][n]=Math.min(t[i-1][n]+1,t[i][n-1]+1,t[i-1][n-1]+o),i>1&&n>1&&r[i-1]===e[n-2]&&r[i-2]===e[n-1]&&(t[i][n]=Math.min(t[i][n],t[i-2][n-2]+1))}return t[r.length][e.length]}function yu(r,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=r.startsWith("--");t&&(r=r.slice(2),e=e.map(s=>s.slice(2)));let n=[],i=3,o=.4;return e.forEach(s=>{if(s.length<=1)return;let a=gu(r,s),l=Math.max(r.length,s.length);(l-a)/l>o&&(a<i?(i=a,n=[s]):a===i&&n.push(s))}),n.sort((s,a)=>s.localeCompare(a)),t&&(n=n.map(s=>`--${s}`)),n.length>1?`
15
15
  (Did you mean one of ${n.join(", ")}?)`:n.length===1?`
16
- (Did you mean ${n[0]}?)`:""}xi.suggestSimilar=yu});var Ai=g(Ar=>{var wu=require("node:events").EventEmitter,_r=require("node:child_process"),he=require("node:path"),gt=require("node:fs"),T=require("node:process"),{Argument:Eu,humanReadableArgName:$u}=ht(),{CommanderError:kr}=We(),{Help:bu,stripColor:Ru}=br(),{Option:ki,DualOptions:Su}=xr(),{suggestSimilar:Oi}=_i(),Or=class r extends wu{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:t=>T.stdout.write(t),writeErr:t=>T.stderr.write(t),outputError:(t,n)=>n(t),getOutHelpWidth:()=>T.stdout.isTTY?T.stdout.columns:void 0,getErrHelpWidth:()=>T.stderr.isTTY?T.stderr.columns:void 0,getOutHasColors:()=>Cr()??(T.stdout.isTTY&&T.stdout.hasColors?.()),getErrHasColors:()=>Cr()??(T.stderr.isTTY&&T.stderr.hasColors?.()),stripColor:t=>Ru(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let i=t,o=n;typeof i=="object"&&i!==null&&(o=i,i=null),o=o||{};let[,s,a]=e.match(/([^ ]+) *(.*)/),l=this.createCommand(s);return i&&(l.description(i),l._executableHandler=!0),o.isDefault&&(this._defaultCommandName=l._name),l._hidden=!!(o.noHelp||o.hidden),l._executableFile=o.executableFile||null,a&&l.arguments(a),this._registerCommand(l),l.parent=this,l.copyInheritedSettings(this),i?this:l}createCommand(e){return new r(e)}createHelp(){return Object.assign(new bu,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
16
+ (Did you mean ${n[0]}?)`:""}xi.suggestSimilar=yu});var Ai=y(Pr=>{var wu=require("node:events").EventEmitter,kr=require("node:child_process"),ge=require("node:path"),ht=require("node:fs"),T=require("node:process"),{Argument:Eu,humanReadableArgName:$u}=pt(),{CommanderError:Or}=Be(),{Help:bu,stripColor:Ru}=Rr(),{Option:ki,DualOptions:Su}=_r(),{suggestSimilar:Oi}=_i(),Cr=class r extends wu{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:t=>T.stdout.write(t),writeErr:t=>T.stderr.write(t),outputError:(t,n)=>n(t),getOutHelpWidth:()=>T.stdout.isTTY?T.stdout.columns:void 0,getErrHelpWidth:()=>T.stderr.isTTY?T.stderr.columns:void 0,getOutHasColors:()=>Ar()??(T.stdout.isTTY&&T.stdout.hasColors?.()),getErrHasColors:()=>Ar()??(T.stderr.isTTY&&T.stderr.hasColors?.()),stripColor:t=>Ru(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let i=t,o=n;typeof i=="object"&&i!==null&&(o=i,i=null),o=o||{};let[,s,a]=e.match(/([^ ]+) *(.*)/),l=this.createCommand(s);return i&&(l.description(i),l._executableHandler=!0),o.isDefault&&(this._defaultCommandName=l._name),l._hidden=!!(o.noHelp||o.hidden),l._executableFile=o.executableFile||null,a&&l.arguments(a),this._registerCommand(l),l.parent=this,l.copyInheritedSettings(this),i?this:l}createCommand(e){return new r(e)}createHelp(){return Object.assign(new bu,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
17
17
  - specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new Eu(e,t)}argument(e,t,n,i){let o=this.createArgument(e,t);return typeof n=="function"?o.default(i).argParser(n):o.default(n),this.addArgument(o),this}arguments(e){return e.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t&&t.variadic)throw new Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,n,i]=e.match(/([^ ]+) *(.*)/),o=t??"display help for command",s=this.createCommand(n);return s.helpOption(!1),i&&s.arguments(i),o&&s.description(o),this._addImplicitHelpCommand=!0,this._helpCommand=s,this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
18
- Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new kr(e,t,n)),T.exit(e)}action(e){let t=n=>{let i=this.registeredArguments.length,o=n.slice(0,i);return this._storeOptionsAsProperties?o[i]=this:o[i]=this.opts(),o.push(this),e.apply(this,o)};return this._actionHandler=t,this}createOption(e,t){return new ki(e,t)}_callParseArg(e,t,n,i){try{return e.parseArg(t,n)}catch(o){if(o.code==="commander.invalidArgument"){let s=`${i} ${o.message}`;this.error(s,{exitCode:o.exitCode,code:o.code})}throw o}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
18
+ Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new Or(e,t,n)),T.exit(e)}action(e){let t=n=>{let i=this.registeredArguments.length,o=n.slice(0,i);return this._storeOptionsAsProperties?o[i]=this:o[i]=this.opts(),o.push(this),e.apply(this,o)};return this._actionHandler=t,this}createOption(e,t){return new ki(e,t)}_callParseArg(e,t,n,i){try{return e.parseArg(t,n)}catch(o){if(o.code==="commander.invalidArgument"){let s=`${i} ${o.message}`;this.error(s,{exitCode:o.exitCode,code:o.code})}throw o}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
19
19
  - already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=i=>[i.name()].concat(i.aliases()),n=t(e).find(i=>this._findCommand(i));if(n){let i=t(this._findCommand(n)).join("|"),o=t(e).join("|");throw new Error(`cannot add command '${o}' as already have command '${i}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();if(e.negate){let o=e.long.replace(/^--no-/,"--");this._findOption(o)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let i=(o,s,a)=>{o==null&&e.presetArg!==void 0&&(o=e.presetArg);let l=this.getOptionValue(n);o!==null&&e.parseArg?o=this._callParseArg(e,o,l,s):o!==null&&e.variadic&&(o=e._concatValue(o,l)),o==null&&(e.negate?o=!1:e.isBoolean()||e.optional?o=!0:o=""),this.setOptionValueWithSource(n,o,a)};return this.on("option:"+t,o=>{let s=`error: option '${e.flags}' argument '${o}' is invalid.`;i(o,s,"cli")}),e.envVar&&this.on("optionEnv:"+t,o=>{let s=`error: option '${e.flags}' value '${o}' from env '${e.envVar}' is invalid.`;i(o,s,"env")}),this}_optionEx(e,t,n,i,o){if(typeof t=="object"&&t instanceof ki)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let s=this.createOption(t,n);if(s.makeOptionMandatory(!!e.mandatory),typeof i=="function")s.default(o).argParser(i);else if(i instanceof RegExp){let a=i;i=(l,u)=>{let c=a.exec(l);return c?c[0]:u},s.default(o).argParser(i)}else s.default(i);return this.addOption(s)}option(e,t,n,i){return this._optionEx({},e,t,n,i)}requiredOption(e,t,n,i){return this._optionEx({mandatory:!0},e,t,n,i)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(t=n.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){T.versions?.electron&&(t.from="electron");let i=T.execArgv??[];(i.includes("-e")||i.includes("--eval")||i.includes("-p")||i.includes("--print"))&&(t.from="eval")}e===void 0&&(e=T.argv),this.rawArgs=e.slice();let n;switch(t.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":T.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;case"eval":n=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_prepareForParse(){this._savedState===null?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
20
- - either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(e,t,n){if(gt.existsSync(e))return;let i=t?`searched for local subcommand relative to directory '${t}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",o=`'${e}' does not exist
20
+ - either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(e,t,n){if(ht.existsSync(e))return;let i=t?`searched for local subcommand relative to directory '${t}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",o=`'${e}' does not exist
21
21
  - if '${n}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
22
22
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
23
- - ${i}`;throw new Error(o)}_executeSubCommand(e,t){t=t.slice();let n=!1,i=[".js",".ts",".tsx",".mjs",".cjs"];function o(c,m){let d=he.resolve(c,m);if(gt.existsSync(d))return d;if(i.includes(he.extname(m)))return;let p=i.find(w=>gt.existsSync(`${d}${w}`));if(p)return`${d}${p}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let c;try{c=gt.realpathSync(this._scriptPath)}catch{c=this._scriptPath}a=he.resolve(he.dirname(c),a)}if(a){let c=o(a,s);if(!c&&!e._executableFile&&this._scriptPath){let m=he.basename(this._scriptPath,he.extname(this._scriptPath));m!==this._name&&(c=o(a,`${m}-${e._name}`))}s=c||s}n=i.includes(he.extname(s));let l;T.platform!=="win32"?n?(t.unshift(s),t=Ci(T.execArgv).concat(t),l=_r.spawn(T.argv[0],t,{stdio:"inherit"})):l=_r.spawn(s,t,{stdio:"inherit"}):(this._checkForMissingExecutable(s,a,e._name),t.unshift(s),t=Ci(T.execArgv).concat(t),l=_r.spawn(T.execPath,t,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(m=>{T.on(m,()=>{l.killed===!1&&l.exitCode===null&&l.kill(m)})});let u=this._exitCallback;l.on("close",c=>{c=c??1,u?u(new kr(c,"commander.executeSubCommandAsync","(close)")):T.exit(c)}),l.on("error",c=>{if(c.code==="ENOENT")this._checkForMissingExecutable(s,a,e._name);else if(c.code==="EACCES")throw new Error(`'${s}' not executable`);if(!u)T.exit(1);else{let m=new kr(1,"commander.executeSubCommandAsync","(error)");m.nestedError=c,u(m)}}),this.runningCommand=l}_dispatchSubcommand(e,t,n){let i=this._findCommand(e);i||this.help({error:!0}),i._prepareForParse();let o;return o=this._chainOrCallSubCommandHook(o,i,"preSubcommand"),o=this._chainOrCall(o,()=>{if(i._executableHandler)this._executeSubCommand(i,t.concat(n));else return i._parseCommand(t,n)}),o}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(n,i,o)=>{let s=i;if(i!==null&&n.parseArg){let a=`error: command-argument value '${i}' is invalid for argument '${n.name()}'.`;s=this._callParseArg(n,i,o,a)}return s};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,i)=>{let o=n.defaultValue;n.variadic?i<this.args.length?(o=this.args.slice(i),n.parseArg&&(o=o.reduce((s,a)=>e(n,a,s),n.defaultValue))):o===void 0&&(o=[]):i<this.args.length&&(o=this.args[i],n.parseArg&&(o=e(n,o,n.defaultValue))),t[i]=o}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e,i=[];return this._getCommandAndAncestors().reverse().filter(o=>o._lifeCycleHooks[t]!==void 0).forEach(o=>{o._lifeCycleHooks[t].forEach(s=>{i.push({hookedCommand:o,callback:s})})}),t==="postAction"&&i.reverse(),i.forEach(o=>{n=this._chainOrCall(n,()=>o.callback(o.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let i=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(o=>{i=this._chainOrCall(i,()=>o(this,t))}),i}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},o=`command:${this.name()}`;if(this._actionHandler){i(),this._processArguments();let s;return s=this._chainOrCallHooks(s,"preAction"),s=this._chainOrCall(s,()=>this._actionHandler(this.processedArgs)),this.parent&&(s=this._chainOrCall(s,()=>{this.parent.emit(o,e,t)})),s=this._chainOrCallHooks(s,"postAction"),s}if(this.parent&&this.parent.listenerCount(o))i(),this._processArguments(),this.parent.emit(o,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(i(),this._processArguments())}else this.commands.length?(i(),this.help({error:!0})):(i(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(n=>{let i=n.attributeName();return this.getOptionValue(i)===void 0?!1:this.getOptionValueSource(i)!=="default"});e.filter(n=>n.conflictsWith.length>0).forEach(n=>{let i=e.find(o=>n.conflictsWith.includes(o.attributeName()));i&&this._conflictingOption(n,i)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],i=t,o=e.slice();function s(l){return l.length>1&&l[0]==="-"}let a=null;for(;o.length;){let l=o.shift();if(l==="--"){i===n&&i.push(l),i.push(...o);break}if(a&&!s(l)){this.emit(`option:${a.name()}`,l);continue}if(a=null,s(l)){let u=this._findOption(l);if(u){if(u.required){let c=o.shift();c===void 0&&this.optionMissingArgument(u),this.emit(`option:${u.name()}`,c)}else if(u.optional){let c=null;o.length>0&&!s(o[0])&&(c=o.shift()),this.emit(`option:${u.name()}`,c)}else this.emit(`option:${u.name()}`);a=u.variadic?u:null;continue}}if(l.length>2&&l[0]==="-"&&l[1]!=="-"){let u=this._findOption(`-${l[1]}`);if(u){u.required||u.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${u.name()}`,l.slice(2)):(this.emit(`option:${u.name()}`),o.unshift(`-${l.slice(2)}`));continue}}if(/^--[^=]+=/.test(l)){let u=l.indexOf("="),c=this._findOption(l.slice(0,u));if(c&&(c.required||c.optional)){this.emit(`option:${c.name()}`,l.slice(u+1));continue}}if(s(l)&&(i=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(l)){t.push(l),o.length>0&&n.push(...o);break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){t.push(l),o.length>0&&t.push(...o);break}else if(this._defaultCommandName){n.push(l),o.length>0&&n.push(...o);break}}if(this._passThroughOptions){i.push(l),o.length>0&&i.push(...o);break}i.push(l)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let i=this.options[n].attributeName();e[i]=i===this._versionOptionName?this._version:this[i]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
23
+ - ${i}`;throw new Error(o)}_executeSubCommand(e,t){t=t.slice();let n=!1,i=[".js",".ts",".tsx",".mjs",".cjs"];function o(c,m){let d=ge.resolve(c,m);if(ht.existsSync(d))return d;if(i.includes(ge.extname(m)))return;let p=i.find(w=>ht.existsSync(`${d}${w}`));if(p)return`${d}${p}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let c;try{c=ht.realpathSync(this._scriptPath)}catch{c=this._scriptPath}a=ge.resolve(ge.dirname(c),a)}if(a){let c=o(a,s);if(!c&&!e._executableFile&&this._scriptPath){let m=ge.basename(this._scriptPath,ge.extname(this._scriptPath));m!==this._name&&(c=o(a,`${m}-${e._name}`))}s=c||s}n=i.includes(ge.extname(s));let l;T.platform!=="win32"?n?(t.unshift(s),t=Ci(T.execArgv).concat(t),l=kr.spawn(T.argv[0],t,{stdio:"inherit"})):l=kr.spawn(s,t,{stdio:"inherit"}):(this._checkForMissingExecutable(s,a,e._name),t.unshift(s),t=Ci(T.execArgv).concat(t),l=kr.spawn(T.execPath,t,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(m=>{T.on(m,()=>{l.killed===!1&&l.exitCode===null&&l.kill(m)})});let u=this._exitCallback;l.on("close",c=>{c=c??1,u?u(new Or(c,"commander.executeSubCommandAsync","(close)")):T.exit(c)}),l.on("error",c=>{if(c.code==="ENOENT")this._checkForMissingExecutable(s,a,e._name);else if(c.code==="EACCES")throw new Error(`'${s}' not executable`);if(!u)T.exit(1);else{let m=new Or(1,"commander.executeSubCommandAsync","(error)");m.nestedError=c,u(m)}}),this.runningCommand=l}_dispatchSubcommand(e,t,n){let i=this._findCommand(e);i||this.help({error:!0}),i._prepareForParse();let o;return o=this._chainOrCallSubCommandHook(o,i,"preSubcommand"),o=this._chainOrCall(o,()=>{if(i._executableHandler)this._executeSubCommand(i,t.concat(n));else return i._parseCommand(t,n)}),o}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(n,i,o)=>{let s=i;if(i!==null&&n.parseArg){let a=`error: command-argument value '${i}' is invalid for argument '${n.name()}'.`;s=this._callParseArg(n,i,o,a)}return s};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,i)=>{let o=n.defaultValue;n.variadic?i<this.args.length?(o=this.args.slice(i),n.parseArg&&(o=o.reduce((s,a)=>e(n,a,s),n.defaultValue))):o===void 0&&(o=[]):i<this.args.length&&(o=this.args[i],n.parseArg&&(o=e(n,o,n.defaultValue))),t[i]=o}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e,i=[];return this._getCommandAndAncestors().reverse().filter(o=>o._lifeCycleHooks[t]!==void 0).forEach(o=>{o._lifeCycleHooks[t].forEach(s=>{i.push({hookedCommand:o,callback:s})})}),t==="postAction"&&i.reverse(),i.forEach(o=>{n=this._chainOrCall(n,()=>o.callback(o.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let i=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(o=>{i=this._chainOrCall(i,()=>o(this,t))}),i}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},o=`command:${this.name()}`;if(this._actionHandler){i(),this._processArguments();let s;return s=this._chainOrCallHooks(s,"preAction"),s=this._chainOrCall(s,()=>this._actionHandler(this.processedArgs)),this.parent&&(s=this._chainOrCall(s,()=>{this.parent.emit(o,e,t)})),s=this._chainOrCallHooks(s,"postAction"),s}if(this.parent&&this.parent.listenerCount(o))i(),this._processArguments(),this.parent.emit(o,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(i(),this._processArguments())}else this.commands.length?(i(),this.help({error:!0})):(i(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(n=>{let i=n.attributeName();return this.getOptionValue(i)===void 0?!1:this.getOptionValueSource(i)!=="default"});e.filter(n=>n.conflictsWith.length>0).forEach(n=>{let i=e.find(o=>n.conflictsWith.includes(o.attributeName()));i&&this._conflictingOption(n,i)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],i=t,o=e.slice();function s(l){return l.length>1&&l[0]==="-"}let a=null;for(;o.length;){let l=o.shift();if(l==="--"){i===n&&i.push(l),i.push(...o);break}if(a&&!s(l)){this.emit(`option:${a.name()}`,l);continue}if(a=null,s(l)){let u=this._findOption(l);if(u){if(u.required){let c=o.shift();c===void 0&&this.optionMissingArgument(u),this.emit(`option:${u.name()}`,c)}else if(u.optional){let c=null;o.length>0&&!s(o[0])&&(c=o.shift()),this.emit(`option:${u.name()}`,c)}else this.emit(`option:${u.name()}`);a=u.variadic?u:null;continue}}if(l.length>2&&l[0]==="-"&&l[1]!=="-"){let u=this._findOption(`-${l[1]}`);if(u){u.required||u.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${u.name()}`,l.slice(2)):(this.emit(`option:${u.name()}`),o.unshift(`-${l.slice(2)}`));continue}}if(/^--[^=]+=/.test(l)){let u=l.indexOf("="),c=this._findOption(l.slice(0,u));if(c&&(c.required||c.optional)){this.emit(`option:${c.name()}`,l.slice(u+1));continue}}if(s(l)&&(i=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(l)){t.push(l),o.length>0&&n.push(...o);break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){t.push(l),o.length>0&&t.push(...o);break}else if(this._defaultCommandName){n.push(l),o.length>0&&n.push(...o);break}}if(this._passThroughOptions){i.push(l),o.length>0&&i.push(...o);break}i.push(l)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let i=this.options[n].attributeName();e[i]=i===this._versionOptionName?this._version:this[i]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
24
24
  `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
25
25
  `):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
26
26
  `),this.outputHelp({error:!0}));let n=t||{},i=n.exitCode||1,o=n.code||"commander.error";this._exit(i,o,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in T.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,T.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Su(this.options),t=n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(i=>!t(i)).forEach(i=>{this.setOptionValueWithSource(i,n.implied[i],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let n=s=>{let a=s.attributeName(),l=this.getOptionValue(a),u=this.options.find(m=>m.negate&&a===m.attributeName()),c=this.options.find(m=>!m.negate&&a===m.attributeName());return u&&(u.presetArg===void 0&&l===!1||u.presetArg!==void 0&&l===u.presetArg)?u:c||s},i=s=>{let a=n(s),l=a.attributeName();return this.getOptionValueSource(l)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},o=`error: ${i(e)} cannot be used with ${i(t)}`;this.error(o,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let i=[],o=this;do{let s=o.createHelp().visibleOptions(o).filter(a=>a.long).map(a=>a.long);i=i.concat(s),o=o.parent}while(o&&!o._enablePositionalOptions);t=Oi(e,i)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?"":"s",o=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${n} but got ${e.length}.`;this.error(o,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let i=[];this.createHelp().visibleCommands(this).forEach(o=>{i.push(o.name()),o.alias()&&i.push(o.alias())}),t=Oi(e,i)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:"commander.unknownCommand"})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",n=n||"output the version number";let i=this.createOption(t,n);return this._versionOptionName=i.attributeName(),this._registerOption(i),this.on("option:"+i.name(),()=>{this._outputConfiguration.writeOut(`${e}
27
- `),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(e);if(n){let i=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${i}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(n=>$u(n));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=he.basename(e,he.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp(),n=this._getOutputContext(e);t.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let i=t.formatHelp(this,t);return n.hasColors?i:this._outputConfiguration.stripColor(i)}_getOutputContext(e){e=e||{};let t=!!e.error,n,i,o;return t?(n=a=>this._outputConfiguration.writeErr(a),i=this._outputConfiguration.getErrHasColors(),o=this._outputConfiguration.getErrHelpWidth()):(n=a=>this._outputConfiguration.writeOut(a),i=this._outputConfiguration.getOutHasColors(),o=this._outputConfiguration.getOutHelpWidth()),{error:t,write:a=>(i||(a=this._outputConfiguration.stripColor(a)),n(a)),hasColors:i,helpWidth:o}}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let n=this._getOutputContext(e),i={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach(s=>s.emit("beforeAllHelp",i)),this.emit("beforeHelp",i);let o=this.helpInformation({error:n.error});if(t&&(o=t(o),typeof o!="string"&&!Buffer.isBuffer(o)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(o),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",i),this._getCommandAndAncestors().forEach(s=>s.emit("afterAllHelp",i))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=Number(T.exitCode??0);t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
27
+ `),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(e);if(n){let i=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${i}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(n=>$u(n));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=ge.basename(e,ge.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp(),n=this._getOutputContext(e);t.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let i=t.formatHelp(this,t);return n.hasColors?i:this._outputConfiguration.stripColor(i)}_getOutputContext(e){e=e||{};let t=!!e.error,n,i,o;return t?(n=a=>this._outputConfiguration.writeErr(a),i=this._outputConfiguration.getErrHasColors(),o=this._outputConfiguration.getErrHelpWidth()):(n=a=>this._outputConfiguration.writeOut(a),i=this._outputConfiguration.getOutHasColors(),o=this._outputConfiguration.getOutHelpWidth()),{error:t,write:a=>(i||(a=this._outputConfiguration.stripColor(a)),n(a)),hasColors:i,helpWidth:o}}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let n=this._getOutputContext(e),i={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach(s=>s.emit("beforeAllHelp",i)),this.emit("beforeHelp",i);let o=this.helpInformation({error:n.error});if(t&&(o=t(o),typeof o!="string"&&!Buffer.isBuffer(o)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(o),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",i),this._getCommandAndAncestors().forEach(s=>s.emit("afterAllHelp",i))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=Number(T.exitCode??0);t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
28
28
  Expecting one of '${n.join("', '")}'`);let i=`${e}Help`;return this.on(i,o=>{let s;typeof t=="function"?s=t({error:o.error,command:o.command}):s=t,s&&o.write(`${s}
29
- `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(i=>t.is(i))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Ci(r){return r.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n="127.0.0.1",i="9229",o;return(o=e.match(/^(--inspect(-brk)?)$/))!==null?t=o[1]:(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=o[1],/^\d+$/.test(o[3])?i=o[3]:n=o[3]):(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=o[1],n=o[3],i=o[4]),t&&i!=="0"?`${t}=${n}:${parseInt(i)+1}`:e})}function Cr(){if(T.env.NO_COLOR||T.env.FORCE_COLOR==="0"||T.env.FORCE_COLOR==="false")return!1;if(T.env.FORCE_COLOR||T.env.CLICOLOR_FORCE!==void 0)return!0}Ar.Command=Or;Ar.useColor=Cr});var yt=g(Z=>{var{Argument:Pi}=ht(),{Command:Pr}=Ai(),{CommanderError:vu,InvalidArgumentError:Ti}=We(),{Help:xu}=br(),{Option:Li}=xr();Z.program=new Pr;Z.createCommand=r=>new Pr(r);Z.createOption=(r,e)=>new Li(r,e);Z.createArgument=(r,e)=>new Pi(r,e);Z.Command=Pr;Z.Option=Li;Z.Argument=Pi;Z.Help=xu;Z.CommanderError=vu;Z.InvalidArgumentError=Ti;Z.InvalidOptionArgumentError=Ti});var Pe=g((Tr,Mi)=>{var wt=require("buffer"),ce=wt.Buffer;function Ii(r,e){for(var t in r)e[t]=r[t]}ce.from&&ce.alloc&&ce.allocUnsafe&&ce.allocUnsafeSlow?Mi.exports=wt:(Ii(wt,Tr),Tr.Buffer=_e);function _e(r,e,t){return ce(r,e,t)}_e.prototype=Object.create(ce.prototype);Ii(ce,_e);_e.from=function(r,e,t){if(typeof r=="number")throw new TypeError("Argument must not be a number");return ce(r,e,t)};_e.alloc=function(r,e,t){if(typeof r!="number")throw new TypeError("Argument must be a number");var n=ce(r);return e!==void 0?typeof t=="string"?n.fill(e,t):n.fill(e):n.fill(0),n};_e.allocUnsafe=function(r){if(typeof r!="number")throw new TypeError("Argument must be a number");return ce(r)};_e.allocUnsafeSlow=function(r){if(typeof r!="number")throw new TypeError("Argument must be a number");return wt.SlowBuffer(r)}});var Lr=g((oE,Ni)=>{var Et=Pe().Buffer,_u=require("stream"),ku=require("util");function $t(r){if(this.buffer=null,this.writable=!0,this.readable=!0,!r)return this.buffer=Et.alloc(0),this;if(typeof r.pipe=="function")return this.buffer=Et.alloc(0),r.pipe(this),this;if(r.length||typeof r=="object")return this.buffer=r,this.writable=!1,process.nextTick(function(){this.emit("end",r),this.readable=!1,this.emit("close")}.bind(this)),this;throw new TypeError("Unexpected data type ("+typeof r+")")}ku.inherits($t,_u);$t.prototype.write=function(e){this.buffer=Et.concat([this.buffer,Et.from(e)]),this.emit("data",e)};$t.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};Ni.exports=$t});var Fi=g((sE,Di)=>{"use strict";function Ir(r){var e=(r/8|0)+(r%8===0?0:1);return e}var Ou={ES256:Ir(256),ES384:Ir(384),ES512:Ir(521)};function Cu(r){var e=Ou[r];if(e)return e;throw new Error('Unknown algorithm "'+r+'"')}Di.exports=Cu});var Wi=g((aE,Hi)=>{"use strict";var bt=Pe().Buffer,ji=Fi(),Rt=128,qi=0,Au=32,Pu=16,Tu=2,Gi=Pu|Au|qi<<6,St=Tu|qi<<6;function Lu(r){return r.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Vi(r){if(bt.isBuffer(r))return r;if(typeof r=="string")return bt.from(r,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function Iu(r,e){r=Vi(r);var t=ji(e),n=t+1,i=r.length,o=0;if(r[o++]!==Gi)throw new Error('Could not find expected "seq"');var s=r[o++];if(s===(Rt|1)&&(s=r[o++]),i-o<s)throw new Error('"seq" specified length of "'+s+'", only "'+(i-o)+'" remaining');if(r[o++]!==St)throw new Error('Could not find expected "int" for "r"');var a=r[o++];if(i-o-2<a)throw new Error('"r" specified length of "'+a+'", only "'+(i-o-2)+'" available');if(n<a)throw new Error('"r" specified length of "'+a+'", max of "'+n+'" is acceptable');var l=o;if(o+=a,r[o++]!==St)throw new Error('Could not find expected "int" for "s"');var u=r[o++];if(i-o!==u)throw new Error('"s" specified length of "'+u+'", expected "'+(i-o)+'"');if(n<u)throw new Error('"s" specified length of "'+u+'", max of "'+n+'" is acceptable');var c=o;if(o+=u,o!==i)throw new Error('Expected to consume entire buffer, but "'+(i-o)+'" bytes remain');var m=t-a,d=t-u,p=bt.allocUnsafe(m+a+d+u);for(o=0;o<m;++o)p[o]=0;r.copy(p,o,l+Math.max(-m,0),l+a),o=t;for(var w=o;o<w+d;++o)p[o]=0;return r.copy(p,o,c+Math.max(-d,0),c+u),p=p.toString("base64"),p=Lu(p),p}function Ui(r,e,t){for(var n=0;e+n<t&&r[e+n]===0;)++n;var i=r[e+n]>=Rt;return i&&--n,n}function Mu(r,e){r=Vi(r);var t=ji(e),n=r.length;if(n!==t*2)throw new TypeError('"'+e+'" signatures must be "'+t*2+'" bytes, saw "'+n+'"');var i=Ui(r,0,t),o=Ui(r,t,r.length),s=t-i,a=t-o,l=2+s+1+1+a,u=l<Rt,c=bt.allocUnsafe((u?2:3)+l),m=0;return c[m++]=Gi,u?c[m++]=l:(c[m++]=Rt|1,c[m++]=l&255),c[m++]=St,c[m++]=s,i<0?(c[m++]=0,m+=r.copy(c,m,0,t)):m+=r.copy(c,m,i,t),c[m++]=St,c[m++]=a,o<0?(c[m++]=0,r.copy(c,m,t)):r.copy(c,m,t+o),c}Hi.exports={derToJose:Iu,joseToDer:Mu}});var Yi=g((lE,Bi)=>{"use strict";var Be=require("buffer").Buffer,Mr=require("buffer").SlowBuffer;Bi.exports=vt;function vt(r,e){if(!Be.isBuffer(r)||!Be.isBuffer(e)||r.length!==e.length)return!1;for(var t=0,n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}vt.install=function(){Be.prototype.equal=Mr.prototype.equal=function(e){return vt(this,e)}};var Nu=Be.prototype.equal,Du=Mr.prototype.equal;vt.restore=function(){Be.prototype.equal=Nu,Mr.prototype.equal=Du}});var Ur=g((cE,ro)=>{var Le=Pe().Buffer,ee=require("crypto"),zi=Wi(),Xi=require("util"),Fu=`"%s" is not a valid algorithm.
29
+ `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(i=>t.is(i))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Ci(r){return r.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n="127.0.0.1",i="9229",o;return(o=e.match(/^(--inspect(-brk)?)$/))!==null?t=o[1]:(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=o[1],/^\d+$/.test(o[3])?i=o[3]:n=o[3]):(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=o[1],n=o[3],i=o[4]),t&&i!=="0"?`${t}=${n}:${parseInt(i)+1}`:e})}function Ar(){if(T.env.NO_COLOR||T.env.FORCE_COLOR==="0"||T.env.FORCE_COLOR==="false")return!1;if(T.env.FORCE_COLOR||T.env.CLICOLOR_FORCE!==void 0)return!0}Pr.Command=Cr;Pr.useColor=Ar});var gt=y(ee=>{var{Argument:Pi}=pt(),{Command:Tr}=Ai(),{CommanderError:vu,InvalidArgumentError:Ti}=Be(),{Help:xu}=Rr(),{Option:Li}=_r();ee.program=new Tr;ee.createCommand=r=>new Tr(r);ee.createOption=(r,e)=>new Li(r,e);ee.createArgument=(r,e)=>new Pi(r,e);ee.Command=Tr;ee.Option=Li;ee.Argument=Pi;ee.Help=xu;ee.CommanderError=vu;ee.InvalidArgumentError=Ti;ee.InvalidOptionArgumentError=Ti});var Te=y((Lr,Mi)=>{var yt=require("buffer"),ce=yt.Buffer;function Ii(r,e){for(var t in r)e[t]=r[t]}ce.from&&ce.alloc&&ce.allocUnsafe&&ce.allocUnsafeSlow?Mi.exports=yt:(Ii(yt,Lr),Lr.Buffer=ke);function ke(r,e,t){return ce(r,e,t)}ke.prototype=Object.create(ce.prototype);Ii(ce,ke);ke.from=function(r,e,t){if(typeof r=="number")throw new TypeError("Argument must not be a number");return ce(r,e,t)};ke.alloc=function(r,e,t){if(typeof r!="number")throw new TypeError("Argument must be a number");var n=ce(r);return e!==void 0?typeof t=="string"?n.fill(e,t):n.fill(e):n.fill(0),n};ke.allocUnsafe=function(r){if(typeof r!="number")throw new TypeError("Argument must be a number");return ce(r)};ke.allocUnsafeSlow=function(r){if(typeof r!="number")throw new TypeError("Argument must be a number");return yt.SlowBuffer(r)}});var Ir=y((oE,Ni)=>{var wt=Te().Buffer,_u=require("stream"),ku=require("util");function Et(r){if(this.buffer=null,this.writable=!0,this.readable=!0,!r)return this.buffer=wt.alloc(0),this;if(typeof r.pipe=="function")return this.buffer=wt.alloc(0),r.pipe(this),this;if(r.length||typeof r=="object")return this.buffer=r,this.writable=!1,process.nextTick(function(){this.emit("end",r),this.readable=!1,this.emit("close")}.bind(this)),this;throw new TypeError("Unexpected data type ("+typeof r+")")}ku.inherits(Et,_u);Et.prototype.write=function(e){this.buffer=wt.concat([this.buffer,wt.from(e)]),this.emit("data",e)};Et.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};Ni.exports=Et});var Fi=y((sE,Di)=>{"use strict";function Mr(r){var e=(r/8|0)+(r%8===0?0:1);return e}var Ou={ES256:Mr(256),ES384:Mr(384),ES512:Mr(521)};function Cu(r){var e=Ou[r];if(e)return e;throw new Error('Unknown algorithm "'+r+'"')}Di.exports=Cu});var Wi=y((aE,Hi)=>{"use strict";var $t=Te().Buffer,ji=Fi(),bt=128,qi=0,Au=32,Pu=16,Tu=2,Gi=Pu|Au|qi<<6,Rt=Tu|qi<<6;function Lu(r){return r.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Vi(r){if($t.isBuffer(r))return r;if(typeof r=="string")return $t.from(r,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function Iu(r,e){r=Vi(r);var t=ji(e),n=t+1,i=r.length,o=0;if(r[o++]!==Gi)throw new Error('Could not find expected "seq"');var s=r[o++];if(s===(bt|1)&&(s=r[o++]),i-o<s)throw new Error('"seq" specified length of "'+s+'", only "'+(i-o)+'" remaining');if(r[o++]!==Rt)throw new Error('Could not find expected "int" for "r"');var a=r[o++];if(i-o-2<a)throw new Error('"r" specified length of "'+a+'", only "'+(i-o-2)+'" available');if(n<a)throw new Error('"r" specified length of "'+a+'", max of "'+n+'" is acceptable');var l=o;if(o+=a,r[o++]!==Rt)throw new Error('Could not find expected "int" for "s"');var u=r[o++];if(i-o!==u)throw new Error('"s" specified length of "'+u+'", expected "'+(i-o)+'"');if(n<u)throw new Error('"s" specified length of "'+u+'", max of "'+n+'" is acceptable');var c=o;if(o+=u,o!==i)throw new Error('Expected to consume entire buffer, but "'+(i-o)+'" bytes remain');var m=t-a,d=t-u,p=$t.allocUnsafe(m+a+d+u);for(o=0;o<m;++o)p[o]=0;r.copy(p,o,l+Math.max(-m,0),l+a),o=t;for(var w=o;o<w+d;++o)p[o]=0;return r.copy(p,o,c+Math.max(-d,0),c+u),p=p.toString("base64"),p=Lu(p),p}function Ui(r,e,t){for(var n=0;e+n<t&&r[e+n]===0;)++n;var i=r[e+n]>=bt;return i&&--n,n}function Mu(r,e){r=Vi(r);var t=ji(e),n=r.length;if(n!==t*2)throw new TypeError('"'+e+'" signatures must be "'+t*2+'" bytes, saw "'+n+'"');var i=Ui(r,0,t),o=Ui(r,t,r.length),s=t-i,a=t-o,l=2+s+1+1+a,u=l<bt,c=$t.allocUnsafe((u?2:3)+l),m=0;return c[m++]=Gi,u?c[m++]=l:(c[m++]=bt|1,c[m++]=l&255),c[m++]=Rt,c[m++]=s,i<0?(c[m++]=0,m+=r.copy(c,m,0,t)):m+=r.copy(c,m,i,t),c[m++]=Rt,c[m++]=a,o<0?(c[m++]=0,r.copy(c,m,t)):r.copy(c,m,t+o),c}Hi.exports={derToJose:Iu,joseToDer:Mu}});var Yi=y((lE,Bi)=>{"use strict";var Ye=require("buffer").Buffer,Nr=require("buffer").SlowBuffer;Bi.exports=St;function St(r,e){if(!Ye.isBuffer(r)||!Ye.isBuffer(e)||r.length!==e.length)return!1;for(var t=0,n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}St.install=function(){Ye.prototype.equal=Nr.prototype.equal=function(e){return St(this,e)}};var Nu=Ye.prototype.equal,Du=Nr.prototype.equal;St.restore=function(){Ye.prototype.equal=Nu,Nr.prototype.equal=Du}});var jr=y((cE,ro)=>{var Ie=Te().Buffer,te=require("crypto"),zi=Wi(),Xi=require("util"),Fu=`"%s" is not a valid algorithm.
30
30
  Supported algorithms are:
31
- "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,Ye="secret must be a string or buffer",Te="key must be a string or a buffer",Uu="key must be a string, a buffer or an object",Dr=typeof ee.createPublicKey=="function";Dr&&(Te+=" or a KeyObject",Ye+="or a KeyObject");function Ji(r){if(!Le.isBuffer(r)&&typeof r!="string"&&(!Dr||typeof r!="object"||typeof r.type!="string"||typeof r.asymmetricKeyType!="string"||typeof r.export!="function"))throw se(Te)}function Ki(r){if(!Le.isBuffer(r)&&typeof r!="string"&&typeof r!="object")throw se(Uu)}function ju(r){if(!Le.isBuffer(r)){if(typeof r=="string")return r;if(!Dr||typeof r!="object"||r.type!=="secret"||typeof r.export!="function")throw se(Ye)}}function Fr(r){return r.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Qi(r){r=r.toString();var e=4-r.length%4;if(e!==4)for(var t=0;t<e;++t)r+="=";return r.replace(/\-/g,"+").replace(/_/g,"/")}function se(r){var e=[].slice.call(arguments,1),t=Xi.format.bind(Xi,r).apply(null,e);return new TypeError(t)}function qu(r){return Le.isBuffer(r)||typeof r=="string"}function Xe(r){return qu(r)||(r=JSON.stringify(r)),r}function Zi(r){return function(t,n){ju(n),t=Xe(t);var i=ee.createHmac("sha"+r,n),o=(i.update(t),i.digest("base64"));return Fr(o)}}var Nr,Gu="timingSafeEqual"in ee?function(e,t){return e.byteLength!==t.byteLength?!1:ee.timingSafeEqual(e,t)}:function(e,t){return Nr||(Nr=Yi()),Nr(e,t)};function Vu(r){return function(t,n,i){var o=Zi(r)(t,i);return Gu(Le.from(n),Le.from(o))}}function eo(r){return function(t,n){Ki(n),t=Xe(t);var i=ee.createSign("RSA-SHA"+r),o=(i.update(t),i.sign(n,"base64"));return Fr(o)}}function to(r){return function(t,n,i){Ji(i),t=Xe(t),n=Qi(n);var o=ee.createVerify("RSA-SHA"+r);return o.update(t),o.verify(i,n,"base64")}}function Hu(r){return function(t,n){Ki(n),t=Xe(t);var i=ee.createSign("RSA-SHA"+r),o=(i.update(t),i.sign({key:n,padding:ee.constants.RSA_PKCS1_PSS_PADDING,saltLength:ee.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return Fr(o)}}function Wu(r){return function(t,n,i){Ji(i),t=Xe(t),n=Qi(n);var o=ee.createVerify("RSA-SHA"+r);return o.update(t),o.verify({key:i,padding:ee.constants.RSA_PKCS1_PSS_PADDING,saltLength:ee.constants.RSA_PSS_SALTLEN_DIGEST},n,"base64")}}function Bu(r){var e=eo(r);return function(){var n=e.apply(null,arguments);return n=zi.derToJose(n,"ES"+r),n}}function Yu(r){var e=to(r);return function(n,i,o){i=zi.joseToDer(i,"ES"+r).toString("base64");var s=e(n,i,o);return s}}function Xu(){return function(){return""}}function zu(){return function(e,t){return t===""}}ro.exports=function(e){var t={hs:Zi,rs:eo,ps:Hu,es:Bu,none:Xu},n={hs:Vu,rs:to,ps:Wu,es:Yu,none:zu},i=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!i)throw se(Fu,e);var o=(i[1]||i[3]).toLowerCase(),s=i[2];return{sign:t[o](s),verify:n[o](s)}}});var jr=g((uE,no)=>{var Ju=require("buffer").Buffer;no.exports=function(e){return typeof e=="string"?e:typeof e=="number"||Ju.isBuffer(e)?e.toString():JSON.stringify(e)}});var co=g((fE,lo)=>{var Ku=Pe().Buffer,io=Lr(),Qu=Ur(),Zu=require("stream"),oo=jr(),qr=require("util");function so(r,e){return Ku.from(r,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function ef(r,e,t){t=t||"utf8";var n=so(oo(r),"binary"),i=so(oo(e),t);return qr.format("%s.%s",n,i)}function ao(r){var e=r.header,t=r.payload,n=r.secret||r.privateKey,i=r.encoding,o=Qu(e.alg),s=ef(e,t,i),a=o.sign(s,n);return qr.format("%s.%s",s,a)}function xt(r){var e=r.secret;if(e=e??r.privateKey,e=e??r.key,/^hs/i.test(r.header.alg)===!0&&e==null)throw new TypeError("secret must be a string or buffer or a KeyObject");var t=new io(e);this.readable=!0,this.header=r.header,this.encoding=r.encoding,this.secret=this.privateKey=this.key=t,this.payload=new io(r.payload),this.secret.once("close",function(){!this.payload.writable&&this.readable&&this.sign()}.bind(this)),this.payload.once("close",function(){!this.secret.writable&&this.readable&&this.sign()}.bind(this))}qr.inherits(xt,Zu);xt.prototype.sign=function(){try{var e=ao({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit("done",e),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(t){this.readable=!1,this.emit("error",t),this.emit("close")}};xt.sign=ao;lo.exports=xt});var $o=g((mE,Eo)=>{var fo=Pe().Buffer,uo=Lr(),tf=Ur(),rf=require("stream"),mo=jr(),nf=require("util"),of=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function sf(r){return Object.prototype.toString.call(r)==="[object Object]"}function af(r){if(sf(r))return r;try{return JSON.parse(r)}catch{return}}function po(r){var e=r.split(".",1)[0];return af(fo.from(e,"base64").toString("binary"))}function lf(r){return r.split(".",2).join(".")}function ho(r){return r.split(".")[2]}function cf(r,e){e=e||"utf8";var t=r.split(".")[1];return fo.from(t,"base64").toString(e)}function go(r){return of.test(r)&&!!po(r)}function yo(r,e,t){if(!e){var n=new Error("Missing algorithm parameter for jws.verify");throw n.code="MISSING_ALGORITHM",n}r=mo(r);var i=ho(r),o=lf(r),s=tf(e);return s.verify(o,i,t)}function wo(r,e){if(e=e||{},r=mo(r),!go(r))return null;var t=po(r);if(!t)return null;var n=cf(r);return(t.typ==="JWT"||e.json)&&(n=JSON.parse(n,e.encoding)),{header:t,payload:n,signature:ho(r)}}function Ie(r){r=r||{};var e=r.secret;if(e=e??r.publicKey,e=e??r.key,/^hs/i.test(r.algorithm)===!0&&e==null)throw new TypeError("secret must be a string or buffer or a KeyObject");var t=new uo(e);this.readable=!0,this.algorithm=r.algorithm,this.encoding=r.encoding,this.secret=this.publicKey=this.key=t,this.signature=new uo(r.signature),this.secret.once("close",function(){!this.signature.writable&&this.readable&&this.verify()}.bind(this)),this.signature.once("close",function(){!this.secret.writable&&this.readable&&this.verify()}.bind(this))}nf.inherits(Ie,rf);Ie.prototype.verify=function(){try{var e=yo(this.signature.buffer,this.algorithm,this.key.buffer),t=wo(this.signature.buffer,this.encoding);return this.emit("done",e,t),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(n){this.readable=!1,this.emit("error",n),this.emit("close")}};Ie.decode=wo;Ie.isValid=go;Ie.verify=yo;Eo.exports=Ie});var kt=g(we=>{var bo=co(),_t=$o(),uf=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];we.ALGORITHMS=uf;we.sign=bo.sign;we.verify=_t.verify;we.decode=_t.decode;we.isValid=_t.isValid;we.createSign=function(e){return new bo(e)};we.createVerify=function(e){return new _t(e)}});var Gr=g((pE,Ro)=>{var ff=kt();Ro.exports=function(r,e){e=e||{};var t=ff.decode(r,e);if(!t)return null;var n=t.payload;if(typeof n=="string")try{var i=JSON.parse(n);i!==null&&typeof i=="object"&&(n=i)}catch{}return e.complete===!0?{header:t.header,payload:n,signature:t.signature}:n}});var ze=g((hE,So)=>{var Ot=function(r,e){Error.call(this,r),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name="JsonWebTokenError",this.message=r,e&&(this.inner=e)};Ot.prototype=Object.create(Error.prototype);Ot.prototype.constructor=Ot;So.exports=Ot});var Vr=g((gE,xo)=>{var vo=ze(),Ct=function(r,e){vo.call(this,r),this.name="NotBeforeError",this.date=e};Ct.prototype=Object.create(vo.prototype);Ct.prototype.constructor=Ct;xo.exports=Ct});var Hr=g((yE,ko)=>{var _o=ze(),At=function(r,e){_o.call(this,r),this.name="TokenExpiredError",this.expiredAt=e};At.prototype=Object.create(_o.prototype);At.prototype.constructor=At;ko.exports=At});var Co=g((wE,Oo)=>{var Me=1e3,Ne=Me*60,De=Ne*60,ke=De*24,mf=ke*7,df=ke*365.25;Oo.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return pf(r);if(t==="number"&&isFinite(r))return e.long?gf(r):hf(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function pf(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(e){var t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*df;case"weeks":case"week":case"w":return t*mf;case"days":case"day":case"d":return t*ke;case"hours":case"hour":case"hrs":case"hr":case"h":return t*De;case"minutes":case"minute":case"mins":case"min":case"m":return t*Ne;case"seconds":case"second":case"secs":case"sec":case"s":return t*Me;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function hf(r){var e=Math.abs(r);return e>=ke?Math.round(r/ke)+"d":e>=De?Math.round(r/De)+"h":e>=Ne?Math.round(r/Ne)+"m":e>=Me?Math.round(r/Me)+"s":r+"ms"}function gf(r){var e=Math.abs(r);return e>=ke?Pt(r,e,ke,"day"):e>=De?Pt(r,e,De,"hour"):e>=Ne?Pt(r,e,Ne,"minute"):e>=Me?Pt(r,e,Me,"second"):r+" ms"}function Pt(r,e,t,n){var i=e>=t*1.5;return Math.round(r/t)+" "+n+(i?"s":"")}});var Wr=g((EE,Ao)=>{var yf=Co();Ao.exports=function(r,e){var t=e||Math.floor(Date.now()/1e3);if(typeof r=="string"){var n=yf(r);return typeof n>"u"?void 0:Math.floor(t+n/1e3)}else return typeof r=="number"?t+r:void 0}});var Fe=g(($E,Po)=>{"use strict";var wf="2.0.0",Ef=Number.MAX_SAFE_INTEGER||9007199254740991,$f=16,bf=250,Rf=["major","premajor","minor","preminor","patch","prepatch","prerelease"];Po.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:$f,MAX_SAFE_BUILD_LENGTH:bf,MAX_SAFE_INTEGER:Ef,RELEASE_TYPES:Rf,SEMVER_SPEC_VERSION:wf,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var Je=g((bE,To)=>{"use strict";var Sf=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{};To.exports=Sf});var Ue=g((ue,Lo)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:Br,MAX_SAFE_BUILD_LENGTH:vf,MAX_LENGTH:xf}=Fe(),_f=Je();ue=Lo.exports={};var kf=ue.re=[],Of=ue.safeRe=[],E=ue.src=[],Cf=ue.safeSrc=[],$=ue.t={},Af=0,Yr="[a-zA-Z0-9-]",Pf=[["\\s",1],["\\d",xf],[Yr,vf]],Tf=r=>{for(let[e,t]of Pf)r=r.split(`${e}*`).join(`${e}{0,${t}}`).split(`${e}+`).join(`${e}{1,${t}}`);return r},v=(r,e,t)=>{let n=Tf(e),i=Af++;_f(r,i,e),$[r]=i,E[i]=e,Cf[i]=n,kf[i]=new RegExp(e,t?"g":void 0),Of[i]=new RegExp(n,t?"g":void 0)};v("NUMERICIDENTIFIER","0|[1-9]\\d*");v("NUMERICIDENTIFIERLOOSE","\\d+");v("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${Yr}*`);v("MAINVERSION",`(${E[$.NUMERICIDENTIFIER]})\\.(${E[$.NUMERICIDENTIFIER]})\\.(${E[$.NUMERICIDENTIFIER]})`);v("MAINVERSIONLOOSE",`(${E[$.NUMERICIDENTIFIERLOOSE]})\\.(${E[$.NUMERICIDENTIFIERLOOSE]})\\.(${E[$.NUMERICIDENTIFIERLOOSE]})`);v("PRERELEASEIDENTIFIER",`(?:${E[$.NONNUMERICIDENTIFIER]}|${E[$.NUMERICIDENTIFIER]})`);v("PRERELEASEIDENTIFIERLOOSE",`(?:${E[$.NONNUMERICIDENTIFIER]}|${E[$.NUMERICIDENTIFIERLOOSE]})`);v("PRERELEASE",`(?:-(${E[$.PRERELEASEIDENTIFIER]}(?:\\.${E[$.PRERELEASEIDENTIFIER]})*))`);v("PRERELEASELOOSE",`(?:-?(${E[$.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${E[$.PRERELEASEIDENTIFIERLOOSE]})*))`);v("BUILDIDENTIFIER",`${Yr}+`);v("BUILD",`(?:\\+(${E[$.BUILDIDENTIFIER]}(?:\\.${E[$.BUILDIDENTIFIER]})*))`);v("FULLPLAIN",`v?${E[$.MAINVERSION]}${E[$.PRERELEASE]}?${E[$.BUILD]}?`);v("FULL",`^${E[$.FULLPLAIN]}$`);v("LOOSEPLAIN",`[v=\\s]*${E[$.MAINVERSIONLOOSE]}${E[$.PRERELEASELOOSE]}?${E[$.BUILD]}?`);v("LOOSE",`^${E[$.LOOSEPLAIN]}$`);v("GTLT","((?:<|>)?=?)");v("XRANGEIDENTIFIERLOOSE",`${E[$.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);v("XRANGEIDENTIFIER",`${E[$.NUMERICIDENTIFIER]}|x|X|\\*`);v("XRANGEPLAIN",`[v=\\s]*(${E[$.XRANGEIDENTIFIER]})(?:\\.(${E[$.XRANGEIDENTIFIER]})(?:\\.(${E[$.XRANGEIDENTIFIER]})(?:${E[$.PRERELEASE]})?${E[$.BUILD]}?)?)?`);v("XRANGEPLAINLOOSE",`[v=\\s]*(${E[$.XRANGEIDENTIFIERLOOSE]})(?:\\.(${E[$.XRANGEIDENTIFIERLOOSE]})(?:\\.(${E[$.XRANGEIDENTIFIERLOOSE]})(?:${E[$.PRERELEASELOOSE]})?${E[$.BUILD]}?)?)?`);v("XRANGE",`^${E[$.GTLT]}\\s*${E[$.XRANGEPLAIN]}$`);v("XRANGELOOSE",`^${E[$.GTLT]}\\s*${E[$.XRANGEPLAINLOOSE]}$`);v("COERCEPLAIN",`(^|[^\\d])(\\d{1,${Br}})(?:\\.(\\d{1,${Br}}))?(?:\\.(\\d{1,${Br}}))?`);v("COERCE",`${E[$.COERCEPLAIN]}(?:$|[^\\d])`);v("COERCEFULL",E[$.COERCEPLAIN]+`(?:${E[$.PRERELEASE]})?(?:${E[$.BUILD]})?(?:$|[^\\d])`);v("COERCERTL",E[$.COERCE],!0);v("COERCERTLFULL",E[$.COERCEFULL],!0);v("LONETILDE","(?:~>?)");v("TILDETRIM",`(\\s*)${E[$.LONETILDE]}\\s+`,!0);ue.tildeTrimReplace="$1~";v("TILDE",`^${E[$.LONETILDE]}${E[$.XRANGEPLAIN]}$`);v("TILDELOOSE",`^${E[$.LONETILDE]}${E[$.XRANGEPLAINLOOSE]}$`);v("LONECARET","(?:\\^)");v("CARETTRIM",`(\\s*)${E[$.LONECARET]}\\s+`,!0);ue.caretTrimReplace="$1^";v("CARET",`^${E[$.LONECARET]}${E[$.XRANGEPLAIN]}$`);v("CARETLOOSE",`^${E[$.LONECARET]}${E[$.XRANGEPLAINLOOSE]}$`);v("COMPARATORLOOSE",`^${E[$.GTLT]}\\s*(${E[$.LOOSEPLAIN]})$|^$`);v("COMPARATOR",`^${E[$.GTLT]}\\s*(${E[$.FULLPLAIN]})$|^$`);v("COMPARATORTRIM",`(\\s*)${E[$.GTLT]}\\s*(${E[$.LOOSEPLAIN]}|${E[$.XRANGEPLAIN]})`,!0);ue.comparatorTrimReplace="$1$2$3";v("HYPHENRANGE",`^\\s*(${E[$.XRANGEPLAIN]})\\s+-\\s+(${E[$.XRANGEPLAIN]})\\s*$`);v("HYPHENRANGELOOSE",`^\\s*(${E[$.XRANGEPLAINLOOSE]})\\s+-\\s+(${E[$.XRANGEPLAINLOOSE]})\\s*$`);v("STAR","(<|>)?=?\\s*\\*");v("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");v("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var Tt=g((RE,Io)=>{"use strict";var Lf=Object.freeze({loose:!0}),If=Object.freeze({}),Mf=r=>r?typeof r!="object"?Lf:r:If;Io.exports=Mf});var Xr=g((SE,Do)=>{"use strict";var Mo=/^[0-9]+$/,No=(r,e)=>{if(typeof r=="number"&&typeof e=="number")return r===e?0:r<e?-1:1;let t=Mo.test(r),n=Mo.test(e);return t&&n&&(r=+r,e=+e),r===e?0:t&&!n?-1:n&&!t?1:r<e?-1:1},Nf=(r,e)=>No(e,r);Do.exports={compareIdentifiers:No,rcompareIdentifiers:Nf}});var W=g((vE,Uo)=>{"use strict";var Lt=Je(),{MAX_LENGTH:Fo,MAX_SAFE_INTEGER:It}=Fe(),{safeRe:Mt,t:Nt}=Ue(),Df=Tt(),{compareIdentifiers:zr}=Xr(),Jr=class r{constructor(e,t){if(t=Df(t),e instanceof r){if(e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease)return e;e=e.version}else if(typeof e!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>Fo)throw new TypeError(`version is longer than ${Fo} characters`);Lt("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;let n=e.trim().match(t.loose?Mt[Nt.LOOSE]:Mt[Nt.FULL]);if(!n)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+n[1],this.minor=+n[2],this.patch=+n[3],this.major>It||this.major<0)throw new TypeError("Invalid major version");if(this.minor>It||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>It||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(i=>{if(/^[0-9]+$/.test(i)){let o=+i;if(o>=0&&o<It)return o}return i}):this.prerelease=[],this.build=n[5]?n[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(e){if(Lt("SemVer.compare",this.version,this.options,e),!(e instanceof r)){if(typeof e=="string"&&e===this.version)return 0;e=new r(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return e instanceof r||(e=new r(e,this.options)),this.major<e.major?-1:this.major>e.major?1:this.minor<e.minor?-1:this.minor>e.minor?1:this.patch<e.patch?-1:this.patch>e.patch?1:0}comparePre(e){if(e instanceof r||(e=new r(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let t=0;do{let n=this.prerelease[t],i=e.prerelease[t];if(Lt("prerelease compare",t,n,i),n===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(n===void 0)return-1;if(n===i)continue;return zr(n,i)}while(++t)}compareBuild(e){e instanceof r||(e=new r(e,this.options));let t=0;do{let n=this.build[t],i=e.build[t];if(Lt("build compare",t,n,i),n===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(n===void 0)return-1;if(n===i)continue;return zr(n,i)}while(++t)}inc(e,t,n){if(e.startsWith("pre")){if(!t&&n===!1)throw new Error("invalid increment argument: identifier is empty");if(t){let i=`-${t}`.match(this.options.loose?Mt[Nt.PRERELEASELOOSE]:Mt[Nt.PRERELEASE]);if(!i||i[1]!==t)throw new Error(`invalid identifier: ${t}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t,n);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t,n);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t,n),this.inc("pre",t,n);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",t,n),this.inc("pre",t,n);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let i=Number(n)?1:0;if(this.prerelease.length===0)this.prerelease=[i];else{let o=this.prerelease.length;for(;--o>=0;)typeof this.prerelease[o]=="number"&&(this.prerelease[o]++,o=-2);if(o===-1){if(t===this.prerelease.join(".")&&n===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(i)}}if(t){let o=[t,i];n===!1&&(o=[t]),zr(this.prerelease[0],t)===0?isNaN(this.prerelease[1])&&(this.prerelease=o):this.prerelease=o}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};Uo.exports=Jr});var Ee=g((xE,qo)=>{"use strict";var jo=W(),Ff=(r,e,t=!1)=>{if(r instanceof jo)return r;try{return new jo(r,e)}catch(n){if(!t)return null;throw n}};qo.exports=Ff});var Vo=g((_E,Go)=>{"use strict";var Uf=Ee(),jf=(r,e)=>{let t=Uf(r,e);return t?t.version:null};Go.exports=jf});var Wo=g((kE,Ho)=>{"use strict";var qf=Ee(),Gf=(r,e)=>{let t=qf(r.trim().replace(/^[=v]+/,""),e);return t?t.version:null};Ho.exports=Gf});var Xo=g((OE,Yo)=>{"use strict";var Bo=W(),Vf=(r,e,t,n,i)=>{typeof t=="string"&&(i=n,n=t,t=void 0);try{return new Bo(r instanceof Bo?r.version:r,t).inc(e,n,i).version}catch{return null}};Yo.exports=Vf});var Ko=g((CE,Jo)=>{"use strict";var zo=Ee(),Hf=(r,e)=>{let t=zo(r,null,!0),n=zo(e,null,!0),i=t.compare(n);if(i===0)return null;let o=i>0,s=o?t:n,a=o?n:t,l=!!s.prerelease.length;if(!!a.prerelease.length&&!l){if(!a.patch&&!a.minor)return"major";if(a.compareMain(s)===0)return a.minor&&!a.patch?"minor":"patch"}let c=l?"pre":"";return t.major!==n.major?c+"major":t.minor!==n.minor?c+"minor":t.patch!==n.patch?c+"patch":"prerelease"};Jo.exports=Hf});var Zo=g((AE,Qo)=>{"use strict";var Wf=W(),Bf=(r,e)=>new Wf(r,e).major;Qo.exports=Bf});var ts=g((PE,es)=>{"use strict";var Yf=W(),Xf=(r,e)=>new Yf(r,e).minor;es.exports=Xf});var ns=g((TE,rs)=>{"use strict";var zf=W(),Jf=(r,e)=>new zf(r,e).patch;rs.exports=Jf});var os=g((LE,is)=>{"use strict";var Kf=Ee(),Qf=(r,e)=>{let t=Kf(r,e);return t&&t.prerelease.length?t.prerelease:null};is.exports=Qf});var te=g((IE,as)=>{"use strict";var ss=W(),Zf=(r,e,t)=>new ss(r,t).compare(new ss(e,t));as.exports=Zf});var cs=g((ME,ls)=>{"use strict";var em=te(),tm=(r,e,t)=>em(e,r,t);ls.exports=tm});var fs=g((NE,us)=>{"use strict";var rm=te(),nm=(r,e)=>rm(r,e,!0);us.exports=nm});var Dt=g((DE,ds)=>{"use strict";var ms=W(),im=(r,e,t)=>{let n=new ms(r,t),i=new ms(e,t);return n.compare(i)||n.compareBuild(i)};ds.exports=im});var hs=g((FE,ps)=>{"use strict";var om=Dt(),sm=(r,e)=>r.sort((t,n)=>om(t,n,e));ps.exports=sm});var ys=g((UE,gs)=>{"use strict";var am=Dt(),lm=(r,e)=>r.sort((t,n)=>am(n,t,e));gs.exports=lm});var Ke=g((jE,ws)=>{"use strict";var cm=te(),um=(r,e,t)=>cm(r,e,t)>0;ws.exports=um});var Ft=g((qE,Es)=>{"use strict";var fm=te(),mm=(r,e,t)=>fm(r,e,t)<0;Es.exports=mm});var Kr=g((GE,$s)=>{"use strict";var dm=te(),pm=(r,e,t)=>dm(r,e,t)===0;$s.exports=pm});var Qr=g((VE,bs)=>{"use strict";var hm=te(),gm=(r,e,t)=>hm(r,e,t)!==0;bs.exports=gm});var Ut=g((HE,Rs)=>{"use strict";var ym=te(),wm=(r,e,t)=>ym(r,e,t)>=0;Rs.exports=wm});var jt=g((WE,Ss)=>{"use strict";var Em=te(),$m=(r,e,t)=>Em(r,e,t)<=0;Ss.exports=$m});var Zr=g((BE,vs)=>{"use strict";var bm=Kr(),Rm=Qr(),Sm=Ke(),vm=Ut(),xm=Ft(),_m=jt(),km=(r,e,t,n)=>{switch(e){case"===":return typeof r=="object"&&(r=r.version),typeof t=="object"&&(t=t.version),r===t;case"!==":return typeof r=="object"&&(r=r.version),typeof t=="object"&&(t=t.version),r!==t;case"":case"=":case"==":return bm(r,t,n);case"!=":return Rm(r,t,n);case">":return Sm(r,t,n);case">=":return vm(r,t,n);case"<":return xm(r,t,n);case"<=":return _m(r,t,n);default:throw new TypeError(`Invalid operator: ${e}`)}};vs.exports=km});var _s=g((YE,xs)=>{"use strict";var Om=W(),Cm=Ee(),{safeRe:qt,t:Gt}=Ue(),Am=(r,e)=>{if(r instanceof Om)return r;if(typeof r=="number"&&(r=String(r)),typeof r!="string")return null;e=e||{};let t=null;if(!e.rtl)t=r.match(e.includePrerelease?qt[Gt.COERCEFULL]:qt[Gt.COERCE]);else{let l=e.includePrerelease?qt[Gt.COERCERTLFULL]:qt[Gt.COERCERTL],u;for(;(u=l.exec(r))&&(!t||t.index+t[0].length!==r.length);)(!t||u.index+u[0].length!==t.index+t[0].length)&&(t=u),l.lastIndex=u.index+u[1].length+u[2].length;l.lastIndex=-1}if(t===null)return null;let n=t[2],i=t[3]||"0",o=t[4]||"0",s=e.includePrerelease&&t[5]?`-${t[5]}`:"",a=e.includePrerelease&&t[6]?`+${t[6]}`:"";return Cm(`${n}.${i}.${o}${s}${a}`,e)};xs.exports=Am});var Os=g((XE,ks)=>{"use strict";var Pm=Ee(),Tm=Fe(),Lm=W(),Im=(r,e,t)=>{if(!Tm.RELEASE_TYPES.includes(e))return null;let n=Mm(r,t);return n&&Nm(n,e)},Mm=(r,e)=>{let t=r instanceof Lm?r.version:r;return Pm(t,e)},Nm=(r,e)=>{if(Dm(e))return r.version;switch(r.prerelease=[],e){case"major":r.minor=0,r.patch=0;break;case"minor":r.patch=0;break}return r.format()},Dm=r=>r.startsWith("pre");ks.exports=Im});var As=g((zE,Cs)=>{"use strict";var en=class{constructor(){this.max=1e3,this.map=new Map}get(e){let t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&t!==void 0){if(this.map.size>=this.max){let i=this.map.keys().next().value;this.delete(i)}this.map.set(e,t)}return this}};Cs.exports=en});var re=g((JE,Is)=>{"use strict";var Fm=/\s+/g,tn=class r{constructor(e,t){if(t=jm(t),e instanceof r)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new r(e.raw,t);if(e instanceof rn)return this.raw=e.value,this.set=[[e]],this.formatted=void 0,this;if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e.trim().replace(Fm," "),this.set=this.raw.split("||").map(n=>this.parseRange(n.trim())).filter(n=>n.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let n=this.set[0];if(this.set=this.set.filter(i=>!Ts(i[0])),this.set.length===0)this.set=[n];else if(this.set.length>1){for(let i of this.set)if(i.length===1&&Ym(i[0])){this.set=[i];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let e=0;e<this.set.length;e++){e>0&&(this.formatted+="||");let t=this.set[e];for(let n=0;n<t.length;n++)n>0&&(this.formatted+=" "),this.formatted+=t[n].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){let n=((this.options.includePrerelease&&Wm)|(this.options.loose&&Bm))+":"+e,i=Ps.get(n);if(i)return i;let o=this.options.loose,s=o?X[B.HYPHENRANGELOOSE]:X[B.HYPHENRANGE];e=e.replace(s,nd(this.options.includePrerelease)),I("hyphen replace",e),e=e.replace(X[B.COMPARATORTRIM],Gm),I("comparator trim",e),e=e.replace(X[B.TILDETRIM],Vm),I("tilde trim",e),e=e.replace(X[B.CARETTRIM],Hm),I("caret trim",e);let a=e.split(" ").map(m=>Xm(m,this.options)).join(" ").split(/\s+/).map(m=>rd(m,this.options));o&&(a=a.filter(m=>(I("loose invalid filter",m,this.options),!!m.match(X[B.COMPARATORLOOSE])))),I("range list",a);let l=new Map,u=a.map(m=>new rn(m,this.options));for(let m of u){if(Ts(m))return[m];l.set(m.value,m)}l.size>1&&l.has("")&&l.delete("");let c=[...l.values()];return Ps.set(n,c),c}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Range is required");return this.set.some(n=>Ls(n,t)&&e.set.some(i=>Ls(i,t)&&n.every(o=>i.every(s=>o.intersects(s,t)))))}test(e){if(!e)return!1;if(typeof e=="string")try{e=new qm(e,this.options)}catch{return!1}for(let t=0;t<this.set.length;t++)if(id(this.set[t],e,this.options))return!0;return!1}};Is.exports=tn;var Um=As(),Ps=new Um,jm=Tt(),rn=Qe(),I=Je(),qm=W(),{safeRe:X,t:B,comparatorTrimReplace:Gm,tildeTrimReplace:Vm,caretTrimReplace:Hm}=Ue(),{FLAG_INCLUDE_PRERELEASE:Wm,FLAG_LOOSE:Bm}=Fe(),Ts=r=>r.value==="<0.0.0-0",Ym=r=>r.value==="",Ls=(r,e)=>{let t=!0,n=r.slice(),i=n.pop();for(;t&&n.length;)t=n.every(o=>i.intersects(o,e)),i=n.pop();return t},Xm=(r,e)=>(r=r.replace(X[B.BUILD],""),I("comp",r,e),r=Km(r,e),I("caret",r),r=zm(r,e),I("tildes",r),r=Zm(r,e),I("xrange",r),r=td(r,e),I("stars",r),r),z=r=>!r||r.toLowerCase()==="x"||r==="*",zm=(r,e)=>r.trim().split(/\s+/).map(t=>Jm(t,e)).join(" "),Jm=(r,e)=>{let t=e.loose?X[B.TILDELOOSE]:X[B.TILDE];return r.replace(t,(n,i,o,s,a)=>{I("tilde",r,n,i,o,s,a);let l;return z(i)?l="":z(o)?l=`>=${i}.0.0 <${+i+1}.0.0-0`:z(s)?l=`>=${i}.${o}.0 <${i}.${+o+1}.0-0`:a?(I("replaceTilde pr",a),l=`>=${i}.${o}.${s}-${a} <${i}.${+o+1}.0-0`):l=`>=${i}.${o}.${s} <${i}.${+o+1}.0-0`,I("tilde return",l),l})},Km=(r,e)=>r.trim().split(/\s+/).map(t=>Qm(t,e)).join(" "),Qm=(r,e)=>{I("caret",r,e);let t=e.loose?X[B.CARETLOOSE]:X[B.CARET],n=e.includePrerelease?"-0":"";return r.replace(t,(i,o,s,a,l)=>{I("caret",r,i,o,s,a,l);let u;return z(o)?u="":z(s)?u=`>=${o}.0.0${n} <${+o+1}.0.0-0`:z(a)?o==="0"?u=`>=${o}.${s}.0${n} <${o}.${+s+1}.0-0`:u=`>=${o}.${s}.0${n} <${+o+1}.0.0-0`:l?(I("replaceCaret pr",l),o==="0"?s==="0"?u=`>=${o}.${s}.${a}-${l} <${o}.${s}.${+a+1}-0`:u=`>=${o}.${s}.${a}-${l} <${o}.${+s+1}.0-0`:u=`>=${o}.${s}.${a}-${l} <${+o+1}.0.0-0`):(I("no pr"),o==="0"?s==="0"?u=`>=${o}.${s}.${a}${n} <${o}.${s}.${+a+1}-0`:u=`>=${o}.${s}.${a}${n} <${o}.${+s+1}.0-0`:u=`>=${o}.${s}.${a} <${+o+1}.0.0-0`),I("caret return",u),u})},Zm=(r,e)=>(I("replaceXRanges",r,e),r.split(/\s+/).map(t=>ed(t,e)).join(" ")),ed=(r,e)=>{r=r.trim();let t=e.loose?X[B.XRANGELOOSE]:X[B.XRANGE];return r.replace(t,(n,i,o,s,a,l)=>{I("xRange",r,n,i,o,s,a,l);let u=z(o),c=u||z(s),m=c||z(a),d=m;return i==="="&&d&&(i=""),l=e.includePrerelease?"-0":"",u?i===">"||i==="<"?n="<0.0.0-0":n="*":i&&d?(c&&(s=0),a=0,i===">"?(i=">=",c?(o=+o+1,s=0,a=0):(s=+s+1,a=0)):i==="<="&&(i="<",c?o=+o+1:s=+s+1),i==="<"&&(l="-0"),n=`${i+o}.${s}.${a}${l}`):c?n=`>=${o}.0.0${l} <${+o+1}.0.0-0`:m&&(n=`>=${o}.${s}.0${l} <${o}.${+s+1}.0-0`),I("xRange return",n),n})},td=(r,e)=>(I("replaceStars",r,e),r.trim().replace(X[B.STAR],"")),rd=(r,e)=>(I("replaceGTE0",r,e),r.trim().replace(X[e.includePrerelease?B.GTE0PRE:B.GTE0],"")),nd=r=>(e,t,n,i,o,s,a,l,u,c,m,d)=>(z(n)?t="":z(i)?t=`>=${n}.0.0${r?"-0":""}`:z(o)?t=`>=${n}.${i}.0${r?"-0":""}`:s?t=`>=${t}`:t=`>=${t}${r?"-0":""}`,z(u)?l="":z(c)?l=`<${+u+1}.0.0-0`:z(m)?l=`<${u}.${+c+1}.0-0`:d?l=`<=${u}.${c}.${m}-${d}`:r?l=`<${u}.${c}.${+m+1}-0`:l=`<=${l}`,`${t} ${l}`.trim()),id=(r,e,t)=>{for(let n=0;n<r.length;n++)if(!r[n].test(e))return!1;if(e.prerelease.length&&!t.includePrerelease){for(let n=0;n<r.length;n++)if(I(r[n].semver),r[n].semver!==rn.ANY&&r[n].semver.prerelease.length>0){let i=r[n].semver;if(i.major===e.major&&i.minor===e.minor&&i.patch===e.patch)return!0}return!1}return!0}});var Qe=g((KE,js)=>{"use strict";var Ze=Symbol("SemVer ANY"),sn=class r{static get ANY(){return Ze}constructor(e,t){if(t=Ms(t),e instanceof r){if(e.loose===!!t.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),on("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===Ze?this.value="":this.value=this.operator+this.semver.version,on("comp",this)}parse(e){let t=this.options.loose?Ns[Ds.COMPARATORLOOSE]:Ns[Ds.COMPARATOR],n=e.match(t);if(!n)throw new TypeError(`Invalid comparator: ${e}`);this.operator=n[1]!==void 0?n[1]:"",this.operator==="="&&(this.operator=""),n[2]?this.semver=new Fs(n[2],this.options.loose):this.semver=Ze}toString(){return this.value}test(e){if(on("Comparator.test",e,this.options.loose),this.semver===Ze||e===Ze)return!0;if(typeof e=="string")try{e=new Fs(e,this.options)}catch{return!1}return nn(e,this.operator,this.semver,this.options)}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new Us(e.value,t).test(this.value):e.operator===""?e.value===""?!0:new Us(this.value,t).test(e.semver):(t=Ms(t),t.includePrerelease&&(this.value==="<0.0.0-0"||e.value==="<0.0.0-0")||!t.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&e.operator.startsWith(">")||this.operator.startsWith("<")&&e.operator.startsWith("<")||this.semver.version===e.semver.version&&this.operator.includes("=")&&e.operator.includes("=")||nn(this.semver,"<",e.semver,t)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||nn(this.semver,">",e.semver,t)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};js.exports=sn;var Ms=Tt(),{safeRe:Ns,t:Ds}=Ue(),nn=Zr(),on=Je(),Fs=W(),Us=re()});var et=g((QE,qs)=>{"use strict";var od=re(),sd=(r,e,t)=>{try{e=new od(e,t)}catch{return!1}return e.test(r)};qs.exports=sd});var Vs=g((ZE,Gs)=>{"use strict";var ad=re(),ld=(r,e)=>new ad(r,e).set.map(t=>t.map(n=>n.value).join(" ").trim().split(" "));Gs.exports=ld});var Ws=g((e$,Hs)=>{"use strict";var cd=W(),ud=re(),fd=(r,e,t)=>{let n=null,i=null,o=null;try{o=new ud(e,t)}catch{return null}return r.forEach(s=>{o.test(s)&&(!n||i.compare(s)===-1)&&(n=s,i=new cd(n,t))}),n};Hs.exports=fd});var Ys=g((t$,Bs)=>{"use strict";var md=W(),dd=re(),pd=(r,e,t)=>{let n=null,i=null,o=null;try{o=new dd(e,t)}catch{return null}return r.forEach(s=>{o.test(s)&&(!n||i.compare(s)===1)&&(n=s,i=new md(n,t))}),n};Bs.exports=pd});var Js=g((r$,zs)=>{"use strict";var an=W(),hd=re(),Xs=Ke(),gd=(r,e)=>{r=new hd(r,e);let t=new an("0.0.0");if(r.test(t)||(t=new an("0.0.0-0"),r.test(t)))return t;t=null;for(let n=0;n<r.set.length;++n){let i=r.set[n],o=null;i.forEach(s=>{let a=new an(s.semver.version);switch(s.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!o||Xs(a,o))&&(o=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${s.operator}`)}}),o&&(!t||Xs(t,o))&&(t=o)}return t&&r.test(t)?t:null};zs.exports=gd});var Qs=g((n$,Ks)=>{"use strict";var yd=re(),wd=(r,e)=>{try{return new yd(r,e).range||"*"}catch{return null}};Ks.exports=wd});var Vt=g((i$,ra)=>{"use strict";var Ed=W(),ta=Qe(),{ANY:$d}=ta,bd=re(),Rd=et(),Zs=Ke(),ea=Ft(),Sd=jt(),vd=Ut(),xd=(r,e,t,n)=>{r=new Ed(r,n),e=new bd(e,n);let i,o,s,a,l;switch(t){case">":i=Zs,o=Sd,s=ea,a=">",l=">=";break;case"<":i=ea,o=vd,s=Zs,a="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(Rd(r,e,n))return!1;for(let u=0;u<e.set.length;++u){let c=e.set[u],m=null,d=null;if(c.forEach(p=>{p.semver===$d&&(p=new ta(">=0.0.0")),m=m||p,d=d||p,i(p.semver,m.semver,n)?m=p:s(p.semver,d.semver,n)&&(d=p)}),m.operator===a||m.operator===l||(!d.operator||d.operator===a)&&o(r,d.semver))return!1;if(d.operator===l&&s(r,d.semver))return!1}return!0};ra.exports=xd});var ia=g((o$,na)=>{"use strict";var _d=Vt(),kd=(r,e,t)=>_d(r,e,">",t);na.exports=kd});var sa=g((s$,oa)=>{"use strict";var Od=Vt(),Cd=(r,e,t)=>Od(r,e,"<",t);oa.exports=Cd});var ca=g((a$,la)=>{"use strict";var aa=re(),Ad=(r,e,t)=>(r=new aa(r,t),e=new aa(e,t),r.intersects(e,t));la.exports=Ad});var fa=g((l$,ua)=>{"use strict";var Pd=et(),Td=te();ua.exports=(r,e,t)=>{let n=[],i=null,o=null,s=r.sort((c,m)=>Td(c,m,t));for(let c of s)Pd(c,e,t)?(o=c,i||(i=c)):(o&&n.push([i,o]),o=null,i=null);i&&n.push([i,null]);let a=[];for(let[c,m]of n)c===m?a.push(c):!m&&c===s[0]?a.push("*"):m?c===s[0]?a.push(`<=${m}`):a.push(`${c} - ${m}`):a.push(`>=${c}`);let l=a.join(" || "),u=typeof e.raw=="string"?e.raw:String(e);return l.length<u.length?l:e}});var ya=g((c$,ga)=>{"use strict";var ma=re(),cn=Qe(),{ANY:ln}=cn,tt=et(),un=te(),Ld=(r,e,t={})=>{if(r===e)return!0;r=new ma(r,t),e=new ma(e,t);let n=!1;e:for(let i of r.set){for(let o of e.set){let s=Md(i,o,t);if(n=n||s!==null,s)continue e}if(n)return!1}return!0},Id=[new cn(">=0.0.0-0")],da=[new cn(">=0.0.0")],Md=(r,e,t)=>{if(r===e)return!0;if(r.length===1&&r[0].semver===ln){if(e.length===1&&e[0].semver===ln)return!0;t.includePrerelease?r=Id:r=da}if(e.length===1&&e[0].semver===ln){if(t.includePrerelease)return!0;e=da}let n=new Set,i,o;for(let p of r)p.operator===">"||p.operator===">="?i=pa(i,p,t):p.operator==="<"||p.operator==="<="?o=ha(o,p,t):n.add(p.semver);if(n.size>1)return null;let s;if(i&&o){if(s=un(i.semver,o.semver,t),s>0)return null;if(s===0&&(i.operator!==">="||o.operator!=="<="))return null}for(let p of n){if(i&&!tt(p,String(i),t)||o&&!tt(p,String(o),t))return null;for(let w of e)if(!tt(p,String(w),t))return!1;return!0}let a,l,u,c,m=o&&!t.includePrerelease&&o.semver.prerelease.length?o.semver:!1,d=i&&!t.includePrerelease&&i.semver.prerelease.length?i.semver:!1;m&&m.prerelease.length===1&&o.operator==="<"&&m.prerelease[0]===0&&(m=!1);for(let p of e){if(c=c||p.operator===">"||p.operator===">=",u=u||p.operator==="<"||p.operator==="<=",i){if(d&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===d.major&&p.semver.minor===d.minor&&p.semver.patch===d.patch&&(d=!1),p.operator===">"||p.operator===">="){if(a=pa(i,p,t),a===p&&a!==i)return!1}else if(i.operator===">="&&!tt(i.semver,String(p),t))return!1}if(o){if(m&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===m.major&&p.semver.minor===m.minor&&p.semver.patch===m.patch&&(m=!1),p.operator==="<"||p.operator==="<="){if(l=ha(o,p,t),l===p&&l!==o)return!1}else if(o.operator==="<="&&!tt(o.semver,String(p),t))return!1}if(!p.operator&&(o||i)&&s!==0)return!1}return!(i&&u&&!o&&s!==0||o&&c&&!i&&s!==0||d||m)},pa=(r,e,t)=>{if(!r)return e;let n=un(r.semver,e.semver,t);return n>0?r:n<0||e.operator===">"&&r.operator===">="?e:r},ha=(r,e,t)=>{if(!r)return e;let n=un(r.semver,e.semver,t);return n<0?r:n>0||e.operator==="<"&&r.operator==="<="?e:r};ga.exports=Ld});var Ht=g((u$,$a)=>{"use strict";var fn=Ue(),wa=Fe(),Nd=W(),Ea=Xr(),Dd=Ee(),Fd=Vo(),Ud=Wo(),jd=Xo(),qd=Ko(),Gd=Zo(),Vd=ts(),Hd=ns(),Wd=os(),Bd=te(),Yd=cs(),Xd=fs(),zd=Dt(),Jd=hs(),Kd=ys(),Qd=Ke(),Zd=Ft(),ep=Kr(),tp=Qr(),rp=Ut(),np=jt(),ip=Zr(),op=_s(),sp=Os(),ap=Qe(),lp=re(),cp=et(),up=Vs(),fp=Ws(),mp=Ys(),dp=Js(),pp=Qs(),hp=Vt(),gp=ia(),yp=sa(),wp=ca(),Ep=fa(),$p=ya();$a.exports={parse:Dd,valid:Fd,clean:Ud,inc:jd,diff:qd,major:Gd,minor:Vd,patch:Hd,prerelease:Wd,compare:Bd,rcompare:Yd,compareLoose:Xd,compareBuild:zd,sort:Jd,rsort:Kd,gt:Qd,lt:Zd,eq:ep,neq:tp,gte:rp,lte:np,cmp:ip,coerce:op,truncate:sp,Comparator:ap,Range:lp,satisfies:cp,toComparators:up,maxSatisfying:fp,minSatisfying:mp,minVersion:dp,validRange:pp,outside:hp,gtr:gp,ltr:yp,intersects:wp,simplifyRange:Ep,subset:$p,SemVer:Nd,re:fn.re,src:fn.src,tokens:fn.t,SEMVER_SPEC_VERSION:wa.SEMVER_SPEC_VERSION,RELEASE_TYPES:wa.RELEASE_TYPES,compareIdentifiers:Ea.compareIdentifiers,rcompareIdentifiers:Ea.rcompareIdentifiers}});var Ra=g((f$,ba)=>{var bp=Ht();ba.exports=bp.satisfies(process.version,">=15.7.0")});var va=g((m$,Sa)=>{var Rp=Ht();Sa.exports=Rp.satisfies(process.version,">=16.9.0")});var mn=g((d$,xa)=>{var Sp=Ra(),vp=va(),xp={ec:["ES256","ES384","ES512"],rsa:["RS256","PS256","RS384","PS384","RS512","PS512"],"rsa-pss":["PS256","PS384","PS512"]},_p={ES256:"prime256v1",ES384:"secp384r1",ES512:"secp521r1"};xa.exports=function(r,e){if(!r||!e)return;let t=e.asymmetricKeyType;if(!t)return;let n=xp[t];if(!n)throw new Error(`Unknown key type "${t}".`);if(!n.includes(r))throw new Error(`"alg" parameter for "${t}" key type must be one of: ${n.join(", ")}.`);if(Sp)switch(t){case"ec":let i=e.asymmetricKeyDetails.namedCurve,o=_p[r];if(i!==o)throw new Error(`"alg" parameter "${r}" requires curve "${o}".`);break;case"rsa-pss":if(vp){let s=parseInt(r.slice(-3),10),{hashAlgorithm:a,mgf1HashAlgorithm:l,saltLength:u}=e.asymmetricKeyDetails;if(a!==`sha${s}`||l!==a)throw new Error(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${r}.`);if(u!==void 0&&u>s>>3)throw new Error(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${r}.`)}break}}});var dn=g((p$,_a)=>{var kp=Ht();_a.exports=kp.satisfies(process.version,"^6.12.0 || >=8.0.0")});var Ca=g((h$,Oa)=>{var L=ze(),Op=Vr(),ka=Hr(),Cp=Gr(),Ap=Wr(),Pp=mn(),Tp=dn(),Lp=kt(),{KeyObject:Ip,createSecretKey:Mp,createPublicKey:Np}=require("crypto"),pn=["RS256","RS384","RS512"],Dp=["ES256","ES384","ES512"],hn=["RS256","RS384","RS512"],Fp=["HS256","HS384","HS512"];Tp&&(pn.splice(pn.length,0,"PS256","PS384","PS512"),hn.splice(hn.length,0,"PS256","PS384","PS512"));Oa.exports=function(r,e,t,n){typeof t=="function"&&!n&&(n=t,t={}),t||(t={}),t=Object.assign({},t);let i;if(n?i=n:i=function(c,m){if(c)throw c;return m},t.clockTimestamp&&typeof t.clockTimestamp!="number")return i(new L("clockTimestamp must be a number"));if(t.nonce!==void 0&&(typeof t.nonce!="string"||t.nonce.trim()===""))return i(new L("nonce must be a non-empty string"));if(t.allowInvalidAsymmetricKeyTypes!==void 0&&typeof t.allowInvalidAsymmetricKeyTypes!="boolean")return i(new L("allowInvalidAsymmetricKeyTypes must be a boolean"));let o=t.clockTimestamp||Math.floor(Date.now()/1e3);if(!r)return i(new L("jwt must be provided"));if(typeof r!="string")return i(new L("jwt must be a string"));let s=r.split(".");if(s.length!==3)return i(new L("jwt malformed"));let a;try{a=Cp(r,{complete:!0})}catch(c){return i(c)}if(!a)return i(new L("invalid token"));let l=a.header,u;if(typeof e=="function"){if(!n)return i(new L("verify must be called asynchronous if secret or public key is provided as a callback"));u=e}else u=function(c,m){return m(null,e)};return u(l,function(c,m){if(c)return i(new L("error in secret or public key callback: "+c.message));let d=s[2].trim()!=="";if(!d&&m)return i(new L("jwt signature is required"));if(d&&!m)return i(new L("secret or public key must be provided"));if(!d&&!t.algorithms)return i(new L('please specify "none" in "algorithms" to verify unsigned tokens'));if(m!=null&&!(m instanceof Ip))try{m=Np(m)}catch{try{m=Mp(typeof m=="string"?Buffer.from(m):m)}catch{return i(new L("secretOrPublicKey is not valid key material"))}}if(t.algorithms||(m.type==="secret"?t.algorithms=Fp:["rsa","rsa-pss"].includes(m.asymmetricKeyType)?t.algorithms=hn:m.asymmetricKeyType==="ec"?t.algorithms=Dp:t.algorithms=pn),t.algorithms.indexOf(a.header.alg)===-1)return i(new L("invalid algorithm"));if(l.alg.startsWith("HS")&&m.type!=="secret")return i(new L(`secretOrPublicKey must be a symmetric key when using ${l.alg}`));if(/^(?:RS|PS|ES)/.test(l.alg)&&m.type!=="public")return i(new L(`secretOrPublicKey must be an asymmetric key when using ${l.alg}`));if(!t.allowInvalidAsymmetricKeyTypes)try{Pp(l.alg,m)}catch(x){return i(x)}let p;try{p=Lp.verify(r,a.header.alg,m)}catch(x){return i(x)}if(!p)return i(new L("invalid signature"));let w=a.payload;if(typeof w.nbf<"u"&&!t.ignoreNotBefore){if(typeof w.nbf!="number")return i(new L("invalid nbf value"));if(w.nbf>o+(t.clockTolerance||0))return i(new Op("jwt not active",new Date(w.nbf*1e3)))}if(typeof w.exp<"u"&&!t.ignoreExpiration){if(typeof w.exp!="number")return i(new L("invalid exp value"));if(o>=w.exp+(t.clockTolerance||0))return i(new ka("jwt expired",new Date(w.exp*1e3)))}if(t.audience){let x=Array.isArray(t.audience)?t.audience:[t.audience];if(!(Array.isArray(w.aud)?w.aud:[w.aud]).some(function(b){return x.some(function(R){return R instanceof RegExp?R.test(b):R===b})}))return i(new L("jwt audience invalid. expected: "+x.join(" or ")))}if(t.issuer&&(typeof t.issuer=="string"&&w.iss!==t.issuer||Array.isArray(t.issuer)&&t.issuer.indexOf(w.iss)===-1))return i(new L("jwt issuer invalid. expected: "+t.issuer));if(t.subject&&w.sub!==t.subject)return i(new L("jwt subject invalid. expected: "+t.subject));if(t.jwtid&&w.jti!==t.jwtid)return i(new L("jwt jwtid invalid. expected: "+t.jwtid));if(t.nonce&&w.nonce!==t.nonce)return i(new L("jwt nonce invalid. expected: "+t.nonce));if(t.maxAge){if(typeof w.iat!="number")return i(new L("iat required when maxAge is specified"));let x=Ap(t.maxAge,w.iat);if(typeof x>"u")return i(new L('"maxAge" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'));if(o>=x+(t.clockTolerance||0))return i(new ka("maxAge exceeded",new Date(x*1e3)))}if(t.complete===!0){let x=a.signature;return i(null,{header:l,payload:w,signature:x})}return i(null,w)})}});var Ma=g((g$,Ia)=>{var Aa=1/0,Ta=9007199254740991,Up=17976931348623157e292,Pa=NaN,jp="[object Arguments]",qp="[object Function]",Gp="[object GeneratorFunction]",Vp="[object String]",Hp="[object Symbol]",Wp=/^\s+|\s+$/g,Bp=/^[-+]0x[0-9a-f]+$/i,Yp=/^0b[01]+$/i,Xp=/^0o[0-7]+$/i,zp=/^(?:0|[1-9]\d*)$/,Jp=parseInt;function Kp(r,e){for(var t=-1,n=r?r.length:0,i=Array(n);++t<n;)i[t]=e(r[t],t,r);return i}function Qp(r,e,t,n){for(var i=r.length,o=t+(n?1:-1);n?o--:++o<i;)if(e(r[o],o,r))return o;return-1}function Zp(r,e,t){if(e!==e)return Qp(r,eh,t);for(var n=t-1,i=r.length;++n<i;)if(r[n]===e)return n;return-1}function eh(r){return r!==r}function th(r,e){for(var t=-1,n=Array(r);++t<r;)n[t]=e(t);return n}function rh(r,e){return Kp(e,function(t){return r[t]})}function nh(r,e){return function(t){return r(e(t))}}var Wt=Object.prototype,yn=Wt.hasOwnProperty,Bt=Wt.toString,ih=Wt.propertyIsEnumerable,oh=nh(Object.keys,Object),sh=Math.max;function ah(r,e){var t=La(r)||mh(r)?th(r.length,String):[],n=t.length,i=!!n;for(var o in r)(e||yn.call(r,o))&&!(i&&(o=="length"||ch(o,n)))&&t.push(o);return t}function lh(r){if(!uh(r))return oh(r);var e=[];for(var t in Object(r))yn.call(r,t)&&t!="constructor"&&e.push(t);return e}function ch(r,e){return e=e??Ta,!!e&&(typeof r=="number"||zp.test(r))&&r>-1&&r%1==0&&r<e}function uh(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||Wt;return r===t}function fh(r,e,t,n){r=wn(r)?r:Rh(r),t=t&&!n?Eh(t):0;var i=r.length;return t<0&&(t=sh(i+t,0)),gh(r)?t<=i&&r.indexOf(e,t)>-1:!!i&&Zp(r,e,t)>-1}function mh(r){return dh(r)&&yn.call(r,"callee")&&(!ih.call(r,"callee")||Bt.call(r)==jp)}var La=Array.isArray;function wn(r){return r!=null&&hh(r.length)&&!ph(r)}function dh(r){return En(r)&&wn(r)}function ph(r){var e=gn(r)?Bt.call(r):"";return e==qp||e==Gp}function hh(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=Ta}function gn(r){var e=typeof r;return!!r&&(e=="object"||e=="function")}function En(r){return!!r&&typeof r=="object"}function gh(r){return typeof r=="string"||!La(r)&&En(r)&&Bt.call(r)==Vp}function yh(r){return typeof r=="symbol"||En(r)&&Bt.call(r)==Hp}function wh(r){if(!r)return r===0?r:0;if(r=$h(r),r===Aa||r===-Aa){var e=r<0?-1:1;return e*Up}return r===r?r:0}function Eh(r){var e=wh(r),t=e%1;return e===e?t?e-t:e:0}function $h(r){if(typeof r=="number")return r;if(yh(r))return Pa;if(gn(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=gn(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=r.replace(Wp,"");var t=Yp.test(r);return t||Xp.test(r)?Jp(r.slice(2),t?2:8):Bp.test(r)?Pa:+r}function bh(r){return wn(r)?ah(r):lh(r)}function Rh(r){return r?rh(r,bh(r)):[]}Ia.exports=fh});var Da=g((y$,Na)=>{var Sh="[object Boolean]",vh=Object.prototype,xh=vh.toString;function _h(r){return r===!0||r===!1||kh(r)&&xh.call(r)==Sh}function kh(r){return!!r&&typeof r=="object"}Na.exports=_h});var Ga=g((w$,qa)=>{var Fa=1/0,Oh=17976931348623157e292,Ua=NaN,Ch="[object Symbol]",Ah=/^\s+|\s+$/g,Ph=/^[-+]0x[0-9a-f]+$/i,Th=/^0b[01]+$/i,Lh=/^0o[0-7]+$/i,Ih=parseInt,Mh=Object.prototype,Nh=Mh.toString;function Dh(r){return typeof r=="number"&&r==qh(r)}function ja(r){var e=typeof r;return!!r&&(e=="object"||e=="function")}function Fh(r){return!!r&&typeof r=="object"}function Uh(r){return typeof r=="symbol"||Fh(r)&&Nh.call(r)==Ch}function jh(r){if(!r)return r===0?r:0;if(r=Gh(r),r===Fa||r===-Fa){var e=r<0?-1:1;return e*Oh}return r===r?r:0}function qh(r){var e=jh(r),t=e%1;return e===e?t?e-t:e:0}function Gh(r){if(typeof r=="number")return r;if(Uh(r))return Ua;if(ja(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=ja(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=r.replace(Ah,"");var t=Th.test(r);return t||Lh.test(r)?Ih(r.slice(2),t?2:8):Ph.test(r)?Ua:+r}qa.exports=Dh});var Ha=g((E$,Va)=>{var Vh="[object Number]",Hh=Object.prototype,Wh=Hh.toString;function Bh(r){return!!r&&typeof r=="object"}function Yh(r){return typeof r=="number"||Bh(r)&&Wh.call(r)==Vh}Va.exports=Yh});var Xa=g(($$,Ya)=>{var Xh="[object Object]";function zh(r){var e=!1;if(r!=null&&typeof r.toString!="function")try{e=!!(r+"")}catch{}return e}function Jh(r,e){return function(t){return r(e(t))}}var Kh=Function.prototype,Wa=Object.prototype,Ba=Kh.toString,Qh=Wa.hasOwnProperty,Zh=Ba.call(Object),eg=Wa.toString,tg=Jh(Object.getPrototypeOf,Object);function rg(r){return!!r&&typeof r=="object"}function ng(r){if(!rg(r)||eg.call(r)!=Xh||zh(r))return!1;var e=tg(r);if(e===null)return!0;var t=Qh.call(e,"constructor")&&e.constructor;return typeof t=="function"&&t instanceof t&&Ba.call(t)==Zh}Ya.exports=ng});var Ja=g((b$,za)=>{var ig="[object String]",og=Object.prototype,sg=og.toString,ag=Array.isArray;function lg(r){return!!r&&typeof r=="object"}function cg(r){return typeof r=="string"||!ag(r)&&lg(r)&&sg.call(r)==ig}za.exports=cg});var tl=g((R$,el)=>{var ug="Expected a function",Ka=1/0,fg=17976931348623157e292,Qa=NaN,mg="[object Symbol]",dg=/^\s+|\s+$/g,pg=/^[-+]0x[0-9a-f]+$/i,hg=/^0b[01]+$/i,gg=/^0o[0-7]+$/i,yg=parseInt,wg=Object.prototype,Eg=wg.toString;function $g(r,e){var t;if(typeof e!="function")throw new TypeError(ug);return r=xg(r),function(){return--r>0&&(t=e.apply(this,arguments)),r<=1&&(e=void 0),t}}function bg(r){return $g(2,r)}function Za(r){var e=typeof r;return!!r&&(e=="object"||e=="function")}function Rg(r){return!!r&&typeof r=="object"}function Sg(r){return typeof r=="symbol"||Rg(r)&&Eg.call(r)==mg}function vg(r){if(!r)return r===0?r:0;if(r=_g(r),r===Ka||r===-Ka){var e=r<0?-1:1;return e*fg}return r===r?r:0}function xg(r){var e=vg(r),t=e%1;return e===e?t?e-t:e:0}function _g(r){if(typeof r=="number")return r;if(Sg(r))return Qa;if(Za(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=Za(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=r.replace(dg,"");var t=hg.test(r);return t||gg.test(r)?yg(r.slice(2),t?2:8):pg.test(r)?Qa:+r}el.exports=bg});var ul=g((S$,cl)=>{var rl=Wr(),kg=dn(),Og=mn(),nl=kt(),Cg=Ma(),Yt=Da(),il=Ga(),$n=Ha(),sl=Xa(),$e=Ja(),Ag=tl(),{KeyObject:Pg,createSecretKey:Tg,createPrivateKey:Lg}=require("crypto"),al=["RS256","RS384","RS512","ES256","ES384","ES512","HS256","HS384","HS512","none"];kg&&al.splice(3,0,"PS256","PS384","PS512");var Ig={expiresIn:{isValid:function(r){return il(r)||$e(r)&&r},message:'"expiresIn" should be a number of seconds or string representing a timespan'},notBefore:{isValid:function(r){return il(r)||$e(r)&&r},message:'"notBefore" should be a number of seconds or string representing a timespan'},audience:{isValid:function(r){return $e(r)||Array.isArray(r)},message:'"audience" must be a string or array'},algorithm:{isValid:Cg.bind(null,al),message:'"algorithm" must be a valid string enum value'},header:{isValid:sl,message:'"header" must be an object'},encoding:{isValid:$e,message:'"encoding" must be a string'},issuer:{isValid:$e,message:'"issuer" must be a string'},subject:{isValid:$e,message:'"subject" must be a string'},jwtid:{isValid:$e,message:'"jwtid" must be a string'},noTimestamp:{isValid:Yt,message:'"noTimestamp" must be a boolean'},keyid:{isValid:$e,message:'"keyid" must be a string'},mutatePayload:{isValid:Yt,message:'"mutatePayload" must be a boolean'},allowInsecureKeySizes:{isValid:Yt,message:'"allowInsecureKeySizes" must be a boolean'},allowInvalidAsymmetricKeyTypes:{isValid:Yt,message:'"allowInvalidAsymmetricKeyTypes" must be a boolean'}},Mg={iat:{isValid:$n,message:'"iat" should be a number of seconds'},exp:{isValid:$n,message:'"exp" should be a number of seconds'},nbf:{isValid:$n,message:'"nbf" should be a number of seconds'}};function ll(r,e,t,n){if(!sl(t))throw new Error('Expected "'+n+'" to be a plain object.');Object.keys(t).forEach(function(i){let o=r[i];if(!o){if(!e)throw new Error('"'+i+'" is not allowed in "'+n+'"');return}if(!o.isValid(t[i]))throw new Error(o.message)})}function Ng(r){return ll(Ig,!1,r,"options")}function Dg(r){return ll(Mg,!0,r,"payload")}var ol={audience:"aud",issuer:"iss",subject:"sub",jwtid:"jti"},Fg=["expiresIn","notBefore","noTimestamp","audience","issuer","subject","jwtid"];cl.exports=function(r,e,t,n){typeof t=="function"?(n=t,t={}):t=t||{};let i=typeof r=="object"&&!Buffer.isBuffer(r),o=Object.assign({alg:t.algorithm||"HS256",typ:i?"JWT":void 0,kid:t.keyid},t.header);function s(u){if(n)return n(u);throw u}if(!e&&t.algorithm!=="none")return s(new Error("secretOrPrivateKey must have a value"));if(e!=null&&!(e instanceof Pg))try{e=Lg(e)}catch{try{e=Tg(typeof e=="string"?Buffer.from(e):e)}catch{return s(new Error("secretOrPrivateKey is not valid key material"))}}if(o.alg.startsWith("HS")&&e.type!=="secret")return s(new Error(`secretOrPrivateKey must be a symmetric key when using ${o.alg}`));if(/^(?:RS|PS|ES)/.test(o.alg)){if(e.type!=="private")return s(new Error(`secretOrPrivateKey must be an asymmetric key when using ${o.alg}`));if(!t.allowInsecureKeySizes&&!o.alg.startsWith("ES")&&e.asymmetricKeyDetails!==void 0&&e.asymmetricKeyDetails.modulusLength<2048)return s(new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${o.alg}`))}if(typeof r>"u")return s(new Error("payload is required"));if(i){try{Dg(r)}catch(u){return s(u)}t.mutatePayload||(r=Object.assign({},r))}else{let u=Fg.filter(function(c){return typeof t[c]<"u"});if(u.length>0)return s(new Error("invalid "+u.join(",")+" option for "+typeof r+" payload"))}if(typeof r.exp<"u"&&typeof t.expiresIn<"u")return s(new Error('Bad "options.expiresIn" option the payload already has an "exp" property.'));if(typeof r.nbf<"u"&&typeof t.notBefore<"u")return s(new Error('Bad "options.notBefore" option the payload already has an "nbf" property.'));try{Ng(t)}catch(u){return s(u)}if(!t.allowInvalidAsymmetricKeyTypes)try{Og(o.alg,e)}catch(u){return s(u)}let a=r.iat||Math.floor(Date.now()/1e3);if(t.noTimestamp?delete r.iat:i&&(r.iat=a),typeof t.notBefore<"u"){try{r.nbf=rl(t.notBefore,a)}catch(u){return s(u)}if(typeof r.nbf>"u")return s(new Error('"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'))}if(typeof t.expiresIn<"u"&&typeof r=="object"){try{r.exp=rl(t.expiresIn,a)}catch(u){return s(u)}if(typeof r.exp>"u")return s(new Error('"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'))}Object.keys(ol).forEach(function(u){let c=ol[u];if(typeof t[u]<"u"){if(typeof r[c]<"u")return s(new Error('Bad "options.'+u+'" option. The payload already has an "'+c+'" property.'));r[c]=t[u]}});let l=t.encoding||"utf8";if(typeof n=="function")n=n&&Ag(n),nl.createSign({header:o,privateKey:e,payload:r,encoding:l}).once("error",n).once("done",function(u){if(!t.allowInsecureKeySizes&&/^(?:RS|PS)/.test(o.alg)&&u.length<256)return n(new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${o.alg}`));n(null,u)});else{let u=nl.sign({header:o,payload:r,secret:e,encoding:l});if(!t.allowInsecureKeySizes&&/^(?:RS|PS)/.test(o.alg)&&u.length<256)throw new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${o.alg}`);return u}}});var bn=g((v$,fl)=>{fl.exports={decode:Gr(),verify:Ca(),sign:ul(),JsonWebTokenError:ze(),NotBeforeError:Vr(),TokenExpiredError:Hr()}});var ql=g((ub,jl)=>{function Ll(r){return Array.isArray(r)?r:[r]}var Nn="",Il=" ",In="\\",by=/^\s+$/,Ry=/(?:[^\\]|^)\\$/,Sy=/^\\!/,vy=/^\\#/,xy=/\r?\n/g,_y=/^\.*\/|^\.+$/,Mn="/",Dl="node-ignore";typeof Symbol<"u"&&(Dl=Symbol.for("node-ignore"));var Ml=Dl,ky=(r,e,t)=>Object.defineProperty(r,e,{value:t}),Oy=/([0-z])-([0-z])/g,Fl=()=>!1,Cy=r=>r.replace(Oy,(e,t,n)=>t.charCodeAt(0)<=n.charCodeAt(0)?e:Nn),Ay=r=>{let{length:e}=r;return r.slice(0,e-e%2)},Py=[[/^\uFEFF/,()=>Nn],[/((?:\\\\)*?)(\\?\s+)$/,(r,e,t)=>e+(t.indexOf("\\")===0?Il:Nn)],[/(\\+?)\s/g,(r,e)=>{let{length:t}=e;return e.slice(0,t-t%2)+Il}],[/[\\$.|*+(){^]/g,r=>`\\${r}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(r,e,t)=>e+6<t.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(r,e,t)=>{let n=t.replace(/\\\*/g,"[^\\/]*");return e+n}],[/\\\\\\(?=[$.|*+(){^])/g,()=>In],[/\\\\/g,()=>In],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(r,e,t,n,i)=>e===In?`\\[${t}${Ay(n)}${i}`:i==="]"&&n.length%2===0?`[${Cy(t)}${n}]`:"[]"],[/(?:[^*])$/,r=>/\/$/.test(r)?`${r}$`:`${r}(?=$|\\/$)`],[/(\^|\\\/)?\\\*$/,(r,e)=>`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`]],Nl=Object.create(null),Ty=(r,e)=>{let t=Nl[r];return t||(t=Py.reduce((n,[i,o])=>n.replace(i,o.bind(r)),r),Nl[r]=t),e?new RegExp(t,"i"):new RegExp(t)},Un=r=>typeof r=="string",Ly=r=>r&&Un(r)&&!by.test(r)&&!Ry.test(r)&&r.indexOf("#")!==0,Iy=r=>r.split(xy),Dn=class{constructor(e,t,n,i){this.origin=e,this.pattern=t,this.negative=n,this.regex=i}},My=(r,e)=>{let t=r,n=!1;r.indexOf("!")===0&&(n=!0,r=r.substr(1)),r=r.replace(Sy,"!").replace(vy,"#");let i=Ty(r,e);return new Dn(t,r,n,i)},Ny=(r,e)=>{throw new e(r)},ge=(r,e,t)=>Un(r)?r?ge.isNotRelative(r)?t(`path should be a \`path.relative()\`d string, but got "${e}"`,RangeError):!0:t("path must not be empty",TypeError):t(`path must be a string, but got \`${e}\``,TypeError),Ul=r=>_y.test(r);ge.isNotRelative=Ul;ge.convert=r=>r;var Fn=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:n=!1}={}){ky(this,Ml,!0),this._rules=[],this._ignoreCase=t,this._allowRelativePaths=n,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}_addPattern(e){if(e&&e[Ml]){this._rules=this._rules.concat(e._rules),this._added=!0;return}if(Ly(e)){let t=My(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,Ll(Un(e)?Iy(e):e).forEach(this._addPattern,this),this._added&&this._initCache(),this}addPattern(e){return this.add(e)}_testOne(e,t){let n=!1,i=!1;return this._rules.forEach(o=>{let{negative:s}=o;if(i===s&&n!==i||s&&!n&&!i&&!t)return;o.regex.test(e)&&(n=!s,i=s)}),{ignored:n,unignored:i}}_test(e,t,n,i){let o=e&&ge.convert(e);return ge(o,e,this._allowRelativePaths?Fl:Ny),this._t(o,t,n,i)}_t(e,t,n,i){if(e in t)return t[e];if(i||(i=e.split(Mn)),i.pop(),!i.length)return t[e]=this._testOne(e,n);let o=this._t(i.join(Mn)+Mn,t,n,i);return t[e]=o.ignored?o:this._testOne(e,n)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return Ll(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},tr=r=>new Fn(r),Dy=r=>ge(r&&ge.convert(r),r,Fl);tr.isPathValid=Dy;tr.default=tr;jl.exports=tr;if(typeof process<"u"&&(process.env&&process.env.IGNORE_TEST_WIN32||process.platform==="win32")){let r=t=>/^\\\\\?\\/.test(t)||/["<>|\u0000-\u001F]+/u.test(t)?t:t.replace(/\\/g,"/");ge.convert=r;let e=/^[a-z]:\//i;ge.isNotRelative=t=>e.test(t)||Ul(t)}});(function(){wi().config(Object.assign({},$i(),Ri()(process.argv)))})();var qc=require("fs"),Gc=require("path");var Uc=O(yt());var ae=O(require("fs")),kn=O(require("path")),gl=O(require("os")),yl=O(bn());var Ug=process.stdout.isTTY===!0&&!process.env.NO_COLOR,be=r=>Ug?r:"",S=be("\x1B[32m"),C=be("\x1B[33m"),_=be("\x1B[36m"),ne=be("\x1B[35m"),h=be("\x1B[31m"),y=be("\x1B[2m"),J=be("\x1B[1m"),f=be("\x1B[0m");var ml="app.boxel.realms";var jg={"anthropic/claude-3.5-sonnet":"Anthropic: Claude 3.5 Sonnet","anthropic/claude-3.7-sonnet":"Anthropic: Claude 3.7 Sonnet","anthropic/claude-3.7-sonnet:thinking":"Anthropic: Claude 3.7 Sonnet (thinking)","anthropic/claude-haiku-4.5":"Anthropic: Claude Haiku 4.5","anthropic/claude-sonnet-4":"Anthropic: Claude Sonnet 4","anthropic/claude-sonnet-4.5":"Anthropic: Claude Sonnet 4.5","anthropic/claude-sonnet-4.6":"Anthropic: Claude Sonnet 4.6","anthropic/claude-opus-4.1":"Anthropic: Claude Opus 4.1","deepseek/deepseek-chat-v3-0324":"DeepSeek: DeepSeek V3 0324","google/gemini-2.5-pro":"Google: Gemini 2.5 Pro","google/gemini-2.5-flash-lite":"Google: Gemini 2.5 Flash Lite","google/gemini-2.5-flash":"Google: Gemini 2.5 Flash","meta-llama/llama-3.2-3b-instruct":"Meta: Llama 3.2 3B Instruct","openai/gpt-4.1-nano":"OpenAI: GPT-4.1 Nano","openai/gpt-4.1-mini":"OpenAI: GPT-4.1 Mini","openai/gpt-4.1":"OpenAI: GPT-4.1","openai/gpt-4o":"OpenAI: GPT-4o","openai/gpt-4o-mini":"OpenAI: GPT-4o-mini","openai/gpt-5-nano":"OpenAI: GPT-5 Nano","openai/gpt-5-mini":"OpenAI: GPT-5 Mini","openai/gpt-5":"OpenAI: GPT-5","openai/gpt-oss-20b":"OpenAI: GPT OSS 20B"},_$=Object.keys(jg);function P(r){return r.endsWith("/")?r:`${r}/`}async function dl(r,e,t){let n=await fetch(new URL("_matrix/client/v3/login",r).href,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({identifier:{type:"m.id.user",user:e},password:t,type:"m.login.password"})}),i=await n.json();if(!n.ok)throw new Error(`Matrix login failed: ${n.status} ${JSON.stringify(i)}`);return{accessToken:i.access_token,deviceId:i.device_id,userId:i.user_id,matrixUrl:r}}async function qg(r){let e=await fetch(new URL(`_matrix/client/v3/user/${encodeURIComponent(r.userId)}/openid/request_token`,r.matrixUrl).href,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r.accessToken}`},body:"{}"});if(!e.ok){let t=await e.text();throw new Error(`OpenID token request failed: ${e.status} ${t}`)}return await e.json()}async function Rn(r,e){let t=await qg(r),n=`${e.replace(/\/$/,"")}/_server-session`,i=await fetch(n,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(t)});if(!i.ok){let s=await i.text();throw new Error(`Realm server session failed: ${i.status} ${s}`)}let o=i.headers.get("Authorization");if(!o)throw new Error("Realm server session response did not include an Authorization header");return o}async function Sn(r,e){let t=`${r.replace(/\/$/,"")}/_realm-auth`,n=await fetch(t,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:e}});if(!n.ok){let i=await n.text();throw new Error(`Realm auth lookup failed: ${n.status} ${i}`)}return await n.json()}function vn(r){return new URL(`_matrix/client/v3/user/${encodeURIComponent(r.userId)}/account_data/${ml}`,r.matrixUrl).href}async function Xt(r){try{let e=await fetch(vn(r),{headers:{Authorization:`Bearer ${r.accessToken}`}});if(!e.ok)return[];let t=await e.json();return Array.isArray(t.realms)?[...t.realms]:[]}catch{return[]}}async function pl(r,e){let t=await Xt(r);if(!t.includes(e)){t.push(e);let n=await fetch(vn(r),{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r.accessToken}`},body:JSON.stringify({realms:t})});if(!n.ok){let i=await n.text();throw new Error(`Failed to update Matrix account data: ${n.status} ${i}`)}}}async function hl(r,e){let t=P(e),n=await Xt(r),i=n.filter(s=>P(s)!==t);if(i.length===n.length)return!1;let o=await fetch(vn(r),{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r.accessToken}`},body:JSON.stringify({realms:i})});if(!o.ok){let s=await o.text();throw new Error(`Failed to update Matrix account data: ${o.status} ${s}`)}return!0}var Gg=kn.join(gl.homedir(),".boxel-cli"),Vg="profiles.json",Hg=86400;function Wg(r,e=Hg){let t=r.replace(/^Bearer\s+/i,""),n=yl.default.decode(t);if(!n?.exp)return!0;let i=Math.floor(Date.now()/1e3);return n.exp-i<e}var M="No active profile. Run `boxel profile add` to create one.";function zt(r){return r.endsWith(":stack.cards")?"staging":r.endsWith(":boxel.ai")?"production":r.endsWith(":localhost")?"local":"unknown"}function je(r){let e=r.match(/^@([^:]+):/);return e?e[1]:r}function Jt(r){let e=r.match(/:([^:]+)$/);return e?e[1]:"unknown"}function fe(r){let e=je(r),t=Jt(r);return`${y}[${f}${_}${e}${f} ${y}\xB7${f} ${ne}${t}${f}${y}]${f}`}var _n=class{config;configDir;profilesFile;constructor(e){this.configDir=e||Gg,this.profilesFile=kn.join(this.configDir,Vg),this.config=this.loadConfig()}ensureConfigDir(){ae.existsSync(this.configDir)||ae.mkdirSync(this.configDir,{recursive:!0})}loadConfig(){let e={profiles:{},activeProfile:null};if(ae.existsSync(this.profilesFile))try{let t=ae.readFileSync(this.profilesFile,"utf-8"),n=JSON.parse(t);if(n&&typeof n=="object"&&!Array.isArray(n)){let i=n,o=i.profiles&&typeof i.profiles=="object"&&!Array.isArray(i.profiles)?i.profiles:null,s=i.activeProfile===null||typeof i.activeProfile=="string"?i.activeProfile:null;if(o)return{profiles:o,activeProfile:s}}}catch{}return e}saveConfig(){this.ensureConfigDir(),ae.writeFileSync(this.profilesFile,JSON.stringify(this.config,null,2),{mode:384});try{ae.chmodSync(this.profilesFile,384)}catch{}}listProfiles(){return Object.keys(this.config.profiles)}getProfile(e){return this.config.profiles[e]}getActiveProfileId(){return this.config.activeProfile}getActiveProfile(){let e=this.config.activeProfile;if(!e)return null;let t=this.config.profiles[e];return t?{id:e,profile:t}:null}async addProfile(e,t,n,i,o){let s=zt(e),a=je(e);if(s==="unknown"&&(!i||!o))throw new Error(`Unknown domain in Matrix ID "${e}". You must provide explicit --matrix-url and --realm-server-url for non-standard domains.`);let l=s==="production"?"https://matrix.boxel.ai":"https://matrix-staging.stack.cards",u=s==="production"?"https://app.boxel.ai/":"https://realms-staging.stack.cards/",c=Jt(e),m={displayName:n||`${a} \xB7 ${c}`,matrixUrl:i||l,realmServerUrl:o||u,password:t};this.config.profiles[e]=m,this.config.activeProfile||(this.config.activeProfile=e),this.saveConfig()}async removeProfile(e){if(!this.config.profiles[e])return!1;if(delete this.config.profiles[e],this.config.activeProfile===e){let t=Object.keys(this.config.profiles);this.config.activeProfile=t.length>0?t[0]:null}return this.saveConfig(),!0}switchProfile(e){return this.config.profiles[e]?(this.config.activeProfile=e,this.saveConfig(),!0):!1}async getActiveCredentials(){let e=this.getActiveProfile();if(e&&e.profile.password)return{matrixUrl:e.profile.matrixUrl,username:je(e.id),password:e.profile.password,realmServerUrl:e.profile.realmServerUrl,profileId:e.id};let t=process.env.MATRIX_URL,n=process.env.MATRIX_USERNAME,i=process.env.MATRIX_PASSWORD,o=process.env.REALM_SERVER_URL;return t&&n&&i&&o?{matrixUrl:t,username:n,password:i,realmServerUrl:o,profileId:null}:null}async getPassword(e){return this.config.profiles[e]?.password||null}async updatePassword(e,t){return this.config.profiles[e]?(this.config.profiles[e].password=t,this.saveConfig(),!0):!1}updateDisplayName(e,t){return this.config.profiles[e]?(this.config.profiles[e].displayName=t,this.saveConfig(),!0):!1}updateUrls(e,t){let n=this.config.profiles[e];if(!n)return!1;let i=!1;return t.matrixUrl&&t.matrixUrl!==n.matrixUrl&&(n.matrixUrl=t.matrixUrl,i=!0),t.realmServerUrl&&t.realmServerUrl!==n.realmServerUrl&&(n.realmServerUrl=t.realmServerUrl,i=!0),i&&(n.realmTokens=void 0,n.realmServerToken=void 0,this.saveConfig()),i}setRealmToken(e,t){let n=this.getActiveProfile();n&&(n.profile.realmTokens||(n.profile.realmTokens={}),n.profile.realmTokens[e]=t,this.saveConfig())}getRealmToken(e){return this.getActiveProfile()?.profile.realmTokens?.[e]}setRealmServerToken(e){let t=this.getActiveProfile();t&&(t.profile.realmServerToken=e,this.saveConfig())}getRealmServerToken(){return this.getActiveProfile()?.profile.realmServerToken}async loginToMatrix(){let e=this.getActiveProfile();if(!e)throw new Error("No active profile");let{id:t,profile:n}=e,i=je(t);return dl(n.matrixUrl,i,n.password)}async getOrRefreshServerToken(){let e=this.getRealmServerToken();if(e&&!Wg(e))return e;let t=await this.loginToMatrix(),i=this.getActiveProfile().profile.realmServerUrl.replace(/\/$/,""),o=await Rn(t,i);return this.setRealmServerToken(o),o}async refreshServerToken(){let e=await this.loginToMatrix(),n=this.getActiveProfile().profile.realmServerUrl.replace(/\/$/,""),i=await Rn(e,n);return this.setRealmServerToken(i),i}findRealmTokenForUrl(e){let n=this.getActiveProfile()?.profile.realmTokens;if(n){for(let[i,o]of Object.entries(n))if(e.startsWith(i)&&o)return o}}async fetchAndStoreAllRealmTokens(){let e=await this.getOrRefreshServerToken(),n=this.getActiveProfile().profile.realmServerUrl.replace(/\/$/,""),i=await Sn(n,e);for(let[o,s]of Object.entries(i))this.setRealmToken(o,s)}async getRealmTokenForUrl(e){let t=this.findRealmTokenForUrl(e);if(t)return t;try{await this.fetchAndStoreAllRealmTokens()}catch{return}return this.findRealmTokenForUrl(e)}buildHeaders(e,t,n){let i=e instanceof Request?new Headers(e.headers):new Headers,o=new Headers(t?.headers);for(let[s,a]of o)i.set(s,a);return i.has("Authorization")||i.set("Authorization",n),i}async authedRealmFetch(e,t){let n=e instanceof Request?e.url:e instanceof URL?e.href:e,i=await this.getRealmTokenForUrl(n);if(i){let l=this.buildHeaders(e,t,i),u=await fetch(e,{...t,headers:l});if(u.status!==401)return u}let o=this.getActiveProfile();if(o&&(o.profile.realmTokens={},o.profile.realmServerToken=void 0,this.saveConfig()),await this.fetchAndStoreAllRealmTokens(),i=this.findRealmTokenForUrl(n),!i)throw new Error(`No realm token available for ${n}. The realm may not be accessible.`);let s=this.buildHeaders(e,t,i);return await fetch(e,{...t,headers:s})}async authedRealmServerFetch(e,t){let n=await this.getOrRefreshServerToken(),i=this.buildHeaders(e,t,n),o=await fetch(e,{...t,headers:i});return o.status===401&&(n=await this.refreshServerToken(),i=this.buildHeaders(e,t,n),o=await fetch(e,{...t,headers:i})),o}async fetchAndStoreRealmToken(e,t){let i=this.getActiveProfile().profile.realmServerUrl.replace(/\/$/,""),s=(await Sn(i,t))[e];return s&&this.setRealmToken(e,s),s}async addToUserRealms(e){let t=await this.loginToMatrix();await pl(t,e)}async removeFromUserRealms(e){let t=await this.loginToMatrix();return hl(t,e)}async getUserRealms(){let e=await this.loginToMatrix();return Xt(e)}async migrateFromEnv(){let e=process.env.MATRIX_URL,t=process.env.MATRIX_USERNAME,n=process.env.MATRIX_PASSWORD,i=process.env.REALM_SERVER_URL;if(!e||!t||!n||!i)return null;let s=e.includes("boxel.ai")?"boxel.ai":"stack.cards",a=`@${t}:${s}`;return this.config.profiles[a]?(this.config.profiles[a].password!==n&&(this.config.profiles[a].password=n,this.saveConfig()),{profileId:a,created:!1}):(await this.addProfile(a,n,void 0,e,i),{profileId:a,created:!0})}printStatus(){let e=this.getActiveProfile();e?(console.log(`
32
- ${J}Active Profile:${f} ${fe(e.id)}`),console.log(` ${y}Display Name:${f} ${e.profile.displayName}`),console.log(` ${y}Matrix URL:${f} ${e.profile.matrixUrl}`),console.log(` ${y}Realm Server:${f} ${e.profile.realmServerUrl}`)):process.env.MATRIX_USERNAME?(console.log(`
33
- ${J}Using environment variables${f} (no profile active)`),console.log(` ${y}Username:${f} ${process.env.MATRIX_USERNAME}`)):(console.log(`
34
- ${C}No active profile and no environment variables set.${f}`),console.log(`Run ${_}boxel profile add${f} to create a profile.`))}},xn=null;function A(){return xn||(xn=new _n),xn}var On=O(require("readline")),wl=require("stream");function K(r){let e=On.createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{e.question(r,n=>{e.close(),t(n.trim())})})}function Cn(r){let e=new wl.Writable({write:(n,i,o)=>o()}),t=On.createInterface({input:process.stdin,output:e,terminal:!0});return new Promise((n,i)=>{let o=process.stdin,s=o.readableFlowing;o.isTTY&&o.setRawMode(!0);let a=()=>{o.removeListener("data",l),o.isTTY&&o.setRawMode(!1),t.close(),s||o.pause()},l=c=>{try{let m=c.toString().split("\x1B[200~").join("").split("\x1B[201~").join("");for(let d of m)if(d===`
31
+ "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,Xe="secret must be a string or buffer",Le="key must be a string or a buffer",Uu="key must be a string, a buffer or an object",Fr=typeof te.createPublicKey=="function";Fr&&(Le+=" or a KeyObject",Xe+="or a KeyObject");function Ji(r){if(!Ie.isBuffer(r)&&typeof r!="string"&&(!Fr||typeof r!="object"||typeof r.type!="string"||typeof r.asymmetricKeyType!="string"||typeof r.export!="function"))throw se(Le)}function Ki(r){if(!Ie.isBuffer(r)&&typeof r!="string"&&typeof r!="object")throw se(Uu)}function ju(r){if(!Ie.isBuffer(r)){if(typeof r=="string")return r;if(!Fr||typeof r!="object"||r.type!=="secret"||typeof r.export!="function")throw se(Xe)}}function Ur(r){return r.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Qi(r){r=r.toString();var e=4-r.length%4;if(e!==4)for(var t=0;t<e;++t)r+="=";return r.replace(/\-/g,"+").replace(/_/g,"/")}function se(r){var e=[].slice.call(arguments,1),t=Xi.format.bind(Xi,r).apply(null,e);return new TypeError(t)}function qu(r){return Ie.isBuffer(r)||typeof r=="string"}function ze(r){return qu(r)||(r=JSON.stringify(r)),r}function Zi(r){return function(t,n){ju(n),t=ze(t);var i=te.createHmac("sha"+r,n),o=(i.update(t),i.digest("base64"));return Ur(o)}}var Dr,Gu="timingSafeEqual"in te?function(e,t){return e.byteLength!==t.byteLength?!1:te.timingSafeEqual(e,t)}:function(e,t){return Dr||(Dr=Yi()),Dr(e,t)};function Vu(r){return function(t,n,i){var o=Zi(r)(t,i);return Gu(Ie.from(n),Ie.from(o))}}function eo(r){return function(t,n){Ki(n),t=ze(t);var i=te.createSign("RSA-SHA"+r),o=(i.update(t),i.sign(n,"base64"));return Ur(o)}}function to(r){return function(t,n,i){Ji(i),t=ze(t),n=Qi(n);var o=te.createVerify("RSA-SHA"+r);return o.update(t),o.verify(i,n,"base64")}}function Hu(r){return function(t,n){Ki(n),t=ze(t);var i=te.createSign("RSA-SHA"+r),o=(i.update(t),i.sign({key:n,padding:te.constants.RSA_PKCS1_PSS_PADDING,saltLength:te.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return Ur(o)}}function Wu(r){return function(t,n,i){Ji(i),t=ze(t),n=Qi(n);var o=te.createVerify("RSA-SHA"+r);return o.update(t),o.verify({key:i,padding:te.constants.RSA_PKCS1_PSS_PADDING,saltLength:te.constants.RSA_PSS_SALTLEN_DIGEST},n,"base64")}}function Bu(r){var e=eo(r);return function(){var n=e.apply(null,arguments);return n=zi.derToJose(n,"ES"+r),n}}function Yu(r){var e=to(r);return function(n,i,o){i=zi.joseToDer(i,"ES"+r).toString("base64");var s=e(n,i,o);return s}}function Xu(){return function(){return""}}function zu(){return function(e,t){return t===""}}ro.exports=function(e){var t={hs:Zi,rs:eo,ps:Hu,es:Bu,none:Xu},n={hs:Vu,rs:to,ps:Wu,es:Yu,none:zu},i=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!i)throw se(Fu,e);var o=(i[1]||i[3]).toLowerCase(),s=i[2];return{sign:t[o](s),verify:n[o](s)}}});var qr=y((uE,no)=>{var Ju=require("buffer").Buffer;no.exports=function(e){return typeof e=="string"?e:typeof e=="number"||Ju.isBuffer(e)?e.toString():JSON.stringify(e)}});var co=y((fE,lo)=>{var Ku=Te().Buffer,io=Ir(),Qu=jr(),Zu=require("stream"),oo=qr(),Gr=require("util");function so(r,e){return Ku.from(r,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function ef(r,e,t){t=t||"utf8";var n=so(oo(r),"binary"),i=so(oo(e),t);return Gr.format("%s.%s",n,i)}function ao(r){var e=r.header,t=r.payload,n=r.secret||r.privateKey,i=r.encoding,o=Qu(e.alg),s=ef(e,t,i),a=o.sign(s,n);return Gr.format("%s.%s",s,a)}function vt(r){var e=r.secret;if(e=e??r.privateKey,e=e??r.key,/^hs/i.test(r.header.alg)===!0&&e==null)throw new TypeError("secret must be a string or buffer or a KeyObject");var t=new io(e);this.readable=!0,this.header=r.header,this.encoding=r.encoding,this.secret=this.privateKey=this.key=t,this.payload=new io(r.payload),this.secret.once("close",function(){!this.payload.writable&&this.readable&&this.sign()}.bind(this)),this.payload.once("close",function(){!this.secret.writable&&this.readable&&this.sign()}.bind(this))}Gr.inherits(vt,Zu);vt.prototype.sign=function(){try{var e=ao({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit("done",e),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(t){this.readable=!1,this.emit("error",t),this.emit("close")}};vt.sign=ao;lo.exports=vt});var $o=y((mE,Eo)=>{var fo=Te().Buffer,uo=Ir(),tf=jr(),rf=require("stream"),mo=qr(),nf=require("util"),of=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function sf(r){return Object.prototype.toString.call(r)==="[object Object]"}function af(r){if(sf(r))return r;try{return JSON.parse(r)}catch{return}}function po(r){var e=r.split(".",1)[0];return af(fo.from(e,"base64").toString("binary"))}function lf(r){return r.split(".",2).join(".")}function ho(r){return r.split(".")[2]}function cf(r,e){e=e||"utf8";var t=r.split(".")[1];return fo.from(t,"base64").toString(e)}function go(r){return of.test(r)&&!!po(r)}function yo(r,e,t){if(!e){var n=new Error("Missing algorithm parameter for jws.verify");throw n.code="MISSING_ALGORITHM",n}r=mo(r);var i=ho(r),o=lf(r),s=tf(e);return s.verify(o,i,t)}function wo(r,e){if(e=e||{},r=mo(r),!go(r))return null;var t=po(r);if(!t)return null;var n=cf(r);return(t.typ==="JWT"||e.json)&&(n=JSON.parse(n,e.encoding)),{header:t,payload:n,signature:ho(r)}}function Me(r){r=r||{};var e=r.secret;if(e=e??r.publicKey,e=e??r.key,/^hs/i.test(r.algorithm)===!0&&e==null)throw new TypeError("secret must be a string or buffer or a KeyObject");var t=new uo(e);this.readable=!0,this.algorithm=r.algorithm,this.encoding=r.encoding,this.secret=this.publicKey=this.key=t,this.signature=new uo(r.signature),this.secret.once("close",function(){!this.signature.writable&&this.readable&&this.verify()}.bind(this)),this.signature.once("close",function(){!this.secret.writable&&this.readable&&this.verify()}.bind(this))}nf.inherits(Me,rf);Me.prototype.verify=function(){try{var e=yo(this.signature.buffer,this.algorithm,this.key.buffer),t=wo(this.signature.buffer,this.encoding);return this.emit("done",e,t),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(n){this.readable=!1,this.emit("error",n),this.emit("close")}};Me.decode=wo;Me.isValid=go;Me.verify=yo;Eo.exports=Me});var _t=y(Ee=>{var bo=co(),xt=$o(),uf=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];Ee.ALGORITHMS=uf;Ee.sign=bo.sign;Ee.verify=xt.verify;Ee.decode=xt.decode;Ee.isValid=xt.isValid;Ee.createSign=function(e){return new bo(e)};Ee.createVerify=function(e){return new xt(e)}});var Vr=y((pE,Ro)=>{var ff=_t();Ro.exports=function(r,e){e=e||{};var t=ff.decode(r,e);if(!t)return null;var n=t.payload;if(typeof n=="string")try{var i=JSON.parse(n);i!==null&&typeof i=="object"&&(n=i)}catch{}return e.complete===!0?{header:t.header,payload:n,signature:t.signature}:n}});var Je=y((hE,So)=>{var kt=function(r,e){Error.call(this,r),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name="JsonWebTokenError",this.message=r,e&&(this.inner=e)};kt.prototype=Object.create(Error.prototype);kt.prototype.constructor=kt;So.exports=kt});var Hr=y((gE,xo)=>{var vo=Je(),Ot=function(r,e){vo.call(this,r),this.name="NotBeforeError",this.date=e};Ot.prototype=Object.create(vo.prototype);Ot.prototype.constructor=Ot;xo.exports=Ot});var Wr=y((yE,ko)=>{var _o=Je(),Ct=function(r,e){_o.call(this,r),this.name="TokenExpiredError",this.expiredAt=e};Ct.prototype=Object.create(_o.prototype);Ct.prototype.constructor=Ct;ko.exports=Ct});var Co=y((wE,Oo)=>{var Ne=1e3,De=Ne*60,Fe=De*60,Oe=Fe*24,mf=Oe*7,df=Oe*365.25;Oo.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return pf(r);if(t==="number"&&isFinite(r))return e.long?gf(r):hf(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function pf(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(e){var t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*df;case"weeks":case"week":case"w":return t*mf;case"days":case"day":case"d":return t*Oe;case"hours":case"hour":case"hrs":case"hr":case"h":return t*Fe;case"minutes":case"minute":case"mins":case"min":case"m":return t*De;case"seconds":case"second":case"secs":case"sec":case"s":return t*Ne;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function hf(r){var e=Math.abs(r);return e>=Oe?Math.round(r/Oe)+"d":e>=Fe?Math.round(r/Fe)+"h":e>=De?Math.round(r/De)+"m":e>=Ne?Math.round(r/Ne)+"s":r+"ms"}function gf(r){var e=Math.abs(r);return e>=Oe?At(r,e,Oe,"day"):e>=Fe?At(r,e,Fe,"hour"):e>=De?At(r,e,De,"minute"):e>=Ne?At(r,e,Ne,"second"):r+" ms"}function At(r,e,t,n){var i=e>=t*1.5;return Math.round(r/t)+" "+n+(i?"s":"")}});var Br=y((EE,Ao)=>{var yf=Co();Ao.exports=function(r,e){var t=e||Math.floor(Date.now()/1e3);if(typeof r=="string"){var n=yf(r);return typeof n>"u"?void 0:Math.floor(t+n/1e3)}else return typeof r=="number"?t+r:void 0}});var Ue=y(($E,Po)=>{"use strict";var wf="2.0.0",Ef=Number.MAX_SAFE_INTEGER||9007199254740991,$f=16,bf=250,Rf=["major","premajor","minor","preminor","patch","prepatch","prerelease"];Po.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:$f,MAX_SAFE_BUILD_LENGTH:bf,MAX_SAFE_INTEGER:Ef,RELEASE_TYPES:Rf,SEMVER_SPEC_VERSION:wf,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var Ke=y((bE,To)=>{"use strict";var Sf=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{};To.exports=Sf});var je=y((ue,Lo)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:Yr,MAX_SAFE_BUILD_LENGTH:vf,MAX_LENGTH:xf}=Ue(),_f=Ke();ue=Lo.exports={};var kf=ue.re=[],Of=ue.safeRe=[],E=ue.src=[],Cf=ue.safeSrc=[],$=ue.t={},Af=0,Xr="[a-zA-Z0-9-]",Pf=[["\\s",1],["\\d",xf],[Xr,vf]],Tf=r=>{for(let[e,t]of Pf)r=r.split(`${e}*`).join(`${e}{0,${t}}`).split(`${e}+`).join(`${e}{1,${t}}`);return r},x=(r,e,t)=>{let n=Tf(e),i=Af++;_f(r,i,e),$[r]=i,E[i]=e,Cf[i]=n,kf[i]=new RegExp(e,t?"g":void 0),Of[i]=new RegExp(n,t?"g":void 0)};x("NUMERICIDENTIFIER","0|[1-9]\\d*");x("NUMERICIDENTIFIERLOOSE","\\d+");x("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${Xr}*`);x("MAINVERSION",`(${E[$.NUMERICIDENTIFIER]})\\.(${E[$.NUMERICIDENTIFIER]})\\.(${E[$.NUMERICIDENTIFIER]})`);x("MAINVERSIONLOOSE",`(${E[$.NUMERICIDENTIFIERLOOSE]})\\.(${E[$.NUMERICIDENTIFIERLOOSE]})\\.(${E[$.NUMERICIDENTIFIERLOOSE]})`);x("PRERELEASEIDENTIFIER",`(?:${E[$.NONNUMERICIDENTIFIER]}|${E[$.NUMERICIDENTIFIER]})`);x("PRERELEASEIDENTIFIERLOOSE",`(?:${E[$.NONNUMERICIDENTIFIER]}|${E[$.NUMERICIDENTIFIERLOOSE]})`);x("PRERELEASE",`(?:-(${E[$.PRERELEASEIDENTIFIER]}(?:\\.${E[$.PRERELEASEIDENTIFIER]})*))`);x("PRERELEASELOOSE",`(?:-?(${E[$.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${E[$.PRERELEASEIDENTIFIERLOOSE]})*))`);x("BUILDIDENTIFIER",`${Xr}+`);x("BUILD",`(?:\\+(${E[$.BUILDIDENTIFIER]}(?:\\.${E[$.BUILDIDENTIFIER]})*))`);x("FULLPLAIN",`v?${E[$.MAINVERSION]}${E[$.PRERELEASE]}?${E[$.BUILD]}?`);x("FULL",`^${E[$.FULLPLAIN]}$`);x("LOOSEPLAIN",`[v=\\s]*${E[$.MAINVERSIONLOOSE]}${E[$.PRERELEASELOOSE]}?${E[$.BUILD]}?`);x("LOOSE",`^${E[$.LOOSEPLAIN]}$`);x("GTLT","((?:<|>)?=?)");x("XRANGEIDENTIFIERLOOSE",`${E[$.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);x("XRANGEIDENTIFIER",`${E[$.NUMERICIDENTIFIER]}|x|X|\\*`);x("XRANGEPLAIN",`[v=\\s]*(${E[$.XRANGEIDENTIFIER]})(?:\\.(${E[$.XRANGEIDENTIFIER]})(?:\\.(${E[$.XRANGEIDENTIFIER]})(?:${E[$.PRERELEASE]})?${E[$.BUILD]}?)?)?`);x("XRANGEPLAINLOOSE",`[v=\\s]*(${E[$.XRANGEIDENTIFIERLOOSE]})(?:\\.(${E[$.XRANGEIDENTIFIERLOOSE]})(?:\\.(${E[$.XRANGEIDENTIFIERLOOSE]})(?:${E[$.PRERELEASELOOSE]})?${E[$.BUILD]}?)?)?`);x("XRANGE",`^${E[$.GTLT]}\\s*${E[$.XRANGEPLAIN]}$`);x("XRANGELOOSE",`^${E[$.GTLT]}\\s*${E[$.XRANGEPLAINLOOSE]}$`);x("COERCEPLAIN",`(^|[^\\d])(\\d{1,${Yr}})(?:\\.(\\d{1,${Yr}}))?(?:\\.(\\d{1,${Yr}}))?`);x("COERCE",`${E[$.COERCEPLAIN]}(?:$|[^\\d])`);x("COERCEFULL",E[$.COERCEPLAIN]+`(?:${E[$.PRERELEASE]})?(?:${E[$.BUILD]})?(?:$|[^\\d])`);x("COERCERTL",E[$.COERCE],!0);x("COERCERTLFULL",E[$.COERCEFULL],!0);x("LONETILDE","(?:~>?)");x("TILDETRIM",`(\\s*)${E[$.LONETILDE]}\\s+`,!0);ue.tildeTrimReplace="$1~";x("TILDE",`^${E[$.LONETILDE]}${E[$.XRANGEPLAIN]}$`);x("TILDELOOSE",`^${E[$.LONETILDE]}${E[$.XRANGEPLAINLOOSE]}$`);x("LONECARET","(?:\\^)");x("CARETTRIM",`(\\s*)${E[$.LONECARET]}\\s+`,!0);ue.caretTrimReplace="$1^";x("CARET",`^${E[$.LONECARET]}${E[$.XRANGEPLAIN]}$`);x("CARETLOOSE",`^${E[$.LONECARET]}${E[$.XRANGEPLAINLOOSE]}$`);x("COMPARATORLOOSE",`^${E[$.GTLT]}\\s*(${E[$.LOOSEPLAIN]})$|^$`);x("COMPARATOR",`^${E[$.GTLT]}\\s*(${E[$.FULLPLAIN]})$|^$`);x("COMPARATORTRIM",`(\\s*)${E[$.GTLT]}\\s*(${E[$.LOOSEPLAIN]}|${E[$.XRANGEPLAIN]})`,!0);ue.comparatorTrimReplace="$1$2$3";x("HYPHENRANGE",`^\\s*(${E[$.XRANGEPLAIN]})\\s+-\\s+(${E[$.XRANGEPLAIN]})\\s*$`);x("HYPHENRANGELOOSE",`^\\s*(${E[$.XRANGEPLAINLOOSE]})\\s+-\\s+(${E[$.XRANGEPLAINLOOSE]})\\s*$`);x("STAR","(<|>)?=?\\s*\\*");x("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");x("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var Pt=y((RE,Io)=>{"use strict";var Lf=Object.freeze({loose:!0}),If=Object.freeze({}),Mf=r=>r?typeof r!="object"?Lf:r:If;Io.exports=Mf});var zr=y((SE,Do)=>{"use strict";var Mo=/^[0-9]+$/,No=(r,e)=>{if(typeof r=="number"&&typeof e=="number")return r===e?0:r<e?-1:1;let t=Mo.test(r),n=Mo.test(e);return t&&n&&(r=+r,e=+e),r===e?0:t&&!n?-1:n&&!t?1:r<e?-1:1},Nf=(r,e)=>No(e,r);Do.exports={compareIdentifiers:No,rcompareIdentifiers:Nf}});var W=y((vE,Uo)=>{"use strict";var Tt=Ke(),{MAX_LENGTH:Fo,MAX_SAFE_INTEGER:Lt}=Ue(),{safeRe:It,t:Mt}=je(),Df=Pt(),{compareIdentifiers:Jr}=zr(),Kr=class r{constructor(e,t){if(t=Df(t),e instanceof r){if(e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease)return e;e=e.version}else if(typeof e!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>Fo)throw new TypeError(`version is longer than ${Fo} characters`);Tt("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;let n=e.trim().match(t.loose?It[Mt.LOOSE]:It[Mt.FULL]);if(!n)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+n[1],this.minor=+n[2],this.patch=+n[3],this.major>Lt||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Lt||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Lt||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(i=>{if(/^[0-9]+$/.test(i)){let o=+i;if(o>=0&&o<Lt)return o}return i}):this.prerelease=[],this.build=n[5]?n[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(e){if(Tt("SemVer.compare",this.version,this.options,e),!(e instanceof r)){if(typeof e=="string"&&e===this.version)return 0;e=new r(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return e instanceof r||(e=new r(e,this.options)),this.major<e.major?-1:this.major>e.major?1:this.minor<e.minor?-1:this.minor>e.minor?1:this.patch<e.patch?-1:this.patch>e.patch?1:0}comparePre(e){if(e instanceof r||(e=new r(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let t=0;do{let n=this.prerelease[t],i=e.prerelease[t];if(Tt("prerelease compare",t,n,i),n===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(n===void 0)return-1;if(n===i)continue;return Jr(n,i)}while(++t)}compareBuild(e){e instanceof r||(e=new r(e,this.options));let t=0;do{let n=this.build[t],i=e.build[t];if(Tt("build compare",t,n,i),n===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(n===void 0)return-1;if(n===i)continue;return Jr(n,i)}while(++t)}inc(e,t,n){if(e.startsWith("pre")){if(!t&&n===!1)throw new Error("invalid increment argument: identifier is empty");if(t){let i=`-${t}`.match(this.options.loose?It[Mt.PRERELEASELOOSE]:It[Mt.PRERELEASE]);if(!i||i[1]!==t)throw new Error(`invalid identifier: ${t}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t,n);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t,n);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t,n),this.inc("pre",t,n);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",t,n),this.inc("pre",t,n);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let i=Number(n)?1:0;if(this.prerelease.length===0)this.prerelease=[i];else{let o=this.prerelease.length;for(;--o>=0;)typeof this.prerelease[o]=="number"&&(this.prerelease[o]++,o=-2);if(o===-1){if(t===this.prerelease.join(".")&&n===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(i)}}if(t){let o=[t,i];n===!1&&(o=[t]),Jr(this.prerelease[0],t)===0?isNaN(this.prerelease[1])&&(this.prerelease=o):this.prerelease=o}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};Uo.exports=Kr});var $e=y((xE,qo)=>{"use strict";var jo=W(),Ff=(r,e,t=!1)=>{if(r instanceof jo)return r;try{return new jo(r,e)}catch(n){if(!t)return null;throw n}};qo.exports=Ff});var Vo=y((_E,Go)=>{"use strict";var Uf=$e(),jf=(r,e)=>{let t=Uf(r,e);return t?t.version:null};Go.exports=jf});var Wo=y((kE,Ho)=>{"use strict";var qf=$e(),Gf=(r,e)=>{let t=qf(r.trim().replace(/^[=v]+/,""),e);return t?t.version:null};Ho.exports=Gf});var Xo=y((OE,Yo)=>{"use strict";var Bo=W(),Vf=(r,e,t,n,i)=>{typeof t=="string"&&(i=n,n=t,t=void 0);try{return new Bo(r instanceof Bo?r.version:r,t).inc(e,n,i).version}catch{return null}};Yo.exports=Vf});var Ko=y((CE,Jo)=>{"use strict";var zo=$e(),Hf=(r,e)=>{let t=zo(r,null,!0),n=zo(e,null,!0),i=t.compare(n);if(i===0)return null;let o=i>0,s=o?t:n,a=o?n:t,l=!!s.prerelease.length;if(!!a.prerelease.length&&!l){if(!a.patch&&!a.minor)return"major";if(a.compareMain(s)===0)return a.minor&&!a.patch?"minor":"patch"}let c=l?"pre":"";return t.major!==n.major?c+"major":t.minor!==n.minor?c+"minor":t.patch!==n.patch?c+"patch":"prerelease"};Jo.exports=Hf});var Zo=y((AE,Qo)=>{"use strict";var Wf=W(),Bf=(r,e)=>new Wf(r,e).major;Qo.exports=Bf});var ts=y((PE,es)=>{"use strict";var Yf=W(),Xf=(r,e)=>new Yf(r,e).minor;es.exports=Xf});var ns=y((TE,rs)=>{"use strict";var zf=W(),Jf=(r,e)=>new zf(r,e).patch;rs.exports=Jf});var os=y((LE,is)=>{"use strict";var Kf=$e(),Qf=(r,e)=>{let t=Kf(r,e);return t&&t.prerelease.length?t.prerelease:null};is.exports=Qf});var re=y((IE,as)=>{"use strict";var ss=W(),Zf=(r,e,t)=>new ss(r,t).compare(new ss(e,t));as.exports=Zf});var cs=y((ME,ls)=>{"use strict";var em=re(),tm=(r,e,t)=>em(e,r,t);ls.exports=tm});var fs=y((NE,us)=>{"use strict";var rm=re(),nm=(r,e)=>rm(r,e,!0);us.exports=nm});var Nt=y((DE,ds)=>{"use strict";var ms=W(),im=(r,e,t)=>{let n=new ms(r,t),i=new ms(e,t);return n.compare(i)||n.compareBuild(i)};ds.exports=im});var hs=y((FE,ps)=>{"use strict";var om=Nt(),sm=(r,e)=>r.sort((t,n)=>om(t,n,e));ps.exports=sm});var ys=y((UE,gs)=>{"use strict";var am=Nt(),lm=(r,e)=>r.sort((t,n)=>am(n,t,e));gs.exports=lm});var Qe=y((jE,ws)=>{"use strict";var cm=re(),um=(r,e,t)=>cm(r,e,t)>0;ws.exports=um});var Dt=y((qE,Es)=>{"use strict";var fm=re(),mm=(r,e,t)=>fm(r,e,t)<0;Es.exports=mm});var Qr=y((GE,$s)=>{"use strict";var dm=re(),pm=(r,e,t)=>dm(r,e,t)===0;$s.exports=pm});var Zr=y((VE,bs)=>{"use strict";var hm=re(),gm=(r,e,t)=>hm(r,e,t)!==0;bs.exports=gm});var Ft=y((HE,Rs)=>{"use strict";var ym=re(),wm=(r,e,t)=>ym(r,e,t)>=0;Rs.exports=wm});var Ut=y((WE,Ss)=>{"use strict";var Em=re(),$m=(r,e,t)=>Em(r,e,t)<=0;Ss.exports=$m});var en=y((BE,vs)=>{"use strict";var bm=Qr(),Rm=Zr(),Sm=Qe(),vm=Ft(),xm=Dt(),_m=Ut(),km=(r,e,t,n)=>{switch(e){case"===":return typeof r=="object"&&(r=r.version),typeof t=="object"&&(t=t.version),r===t;case"!==":return typeof r=="object"&&(r=r.version),typeof t=="object"&&(t=t.version),r!==t;case"":case"=":case"==":return bm(r,t,n);case"!=":return Rm(r,t,n);case">":return Sm(r,t,n);case">=":return vm(r,t,n);case"<":return xm(r,t,n);case"<=":return _m(r,t,n);default:throw new TypeError(`Invalid operator: ${e}`)}};vs.exports=km});var _s=y((YE,xs)=>{"use strict";var Om=W(),Cm=$e(),{safeRe:jt,t:qt}=je(),Am=(r,e)=>{if(r instanceof Om)return r;if(typeof r=="number"&&(r=String(r)),typeof r!="string")return null;e=e||{};let t=null;if(!e.rtl)t=r.match(e.includePrerelease?jt[qt.COERCEFULL]:jt[qt.COERCE]);else{let l=e.includePrerelease?jt[qt.COERCERTLFULL]:jt[qt.COERCERTL],u;for(;(u=l.exec(r))&&(!t||t.index+t[0].length!==r.length);)(!t||u.index+u[0].length!==t.index+t[0].length)&&(t=u),l.lastIndex=u.index+u[1].length+u[2].length;l.lastIndex=-1}if(t===null)return null;let n=t[2],i=t[3]||"0",o=t[4]||"0",s=e.includePrerelease&&t[5]?`-${t[5]}`:"",a=e.includePrerelease&&t[6]?`+${t[6]}`:"";return Cm(`${n}.${i}.${o}${s}${a}`,e)};xs.exports=Am});var Os=y((XE,ks)=>{"use strict";var Pm=$e(),Tm=Ue(),Lm=W(),Im=(r,e,t)=>{if(!Tm.RELEASE_TYPES.includes(e))return null;let n=Mm(r,t);return n&&Nm(n,e)},Mm=(r,e)=>{let t=r instanceof Lm?r.version:r;return Pm(t,e)},Nm=(r,e)=>{if(Dm(e))return r.version;switch(r.prerelease=[],e){case"major":r.minor=0,r.patch=0;break;case"minor":r.patch=0;break}return r.format()},Dm=r=>r.startsWith("pre");ks.exports=Im});var As=y((zE,Cs)=>{"use strict";var tn=class{constructor(){this.max=1e3,this.map=new Map}get(e){let t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&t!==void 0){if(this.map.size>=this.max){let i=this.map.keys().next().value;this.delete(i)}this.map.set(e,t)}return this}};Cs.exports=tn});var ne=y((JE,Is)=>{"use strict";var Fm=/\s+/g,rn=class r{constructor(e,t){if(t=jm(t),e instanceof r)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new r(e.raw,t);if(e instanceof nn)return this.raw=e.value,this.set=[[e]],this.formatted=void 0,this;if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e.trim().replace(Fm," "),this.set=this.raw.split("||").map(n=>this.parseRange(n.trim())).filter(n=>n.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let n=this.set[0];if(this.set=this.set.filter(i=>!Ts(i[0])),this.set.length===0)this.set=[n];else if(this.set.length>1){for(let i of this.set)if(i.length===1&&Ym(i[0])){this.set=[i];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let e=0;e<this.set.length;e++){e>0&&(this.formatted+="||");let t=this.set[e];for(let n=0;n<t.length;n++)n>0&&(this.formatted+=" "),this.formatted+=t[n].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){let n=((this.options.includePrerelease&&Wm)|(this.options.loose&&Bm))+":"+e,i=Ps.get(n);if(i)return i;let o=this.options.loose,s=o?z[Y.HYPHENRANGELOOSE]:z[Y.HYPHENRANGE];e=e.replace(s,nd(this.options.includePrerelease)),I("hyphen replace",e),e=e.replace(z[Y.COMPARATORTRIM],Gm),I("comparator trim",e),e=e.replace(z[Y.TILDETRIM],Vm),I("tilde trim",e),e=e.replace(z[Y.CARETTRIM],Hm),I("caret trim",e);let a=e.split(" ").map(m=>Xm(m,this.options)).join(" ").split(/\s+/).map(m=>rd(m,this.options));o&&(a=a.filter(m=>(I("loose invalid filter",m,this.options),!!m.match(z[Y.COMPARATORLOOSE])))),I("range list",a);let l=new Map,u=a.map(m=>new nn(m,this.options));for(let m of u){if(Ts(m))return[m];l.set(m.value,m)}l.size>1&&l.has("")&&l.delete("");let c=[...l.values()];return Ps.set(n,c),c}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Range is required");return this.set.some(n=>Ls(n,t)&&e.set.some(i=>Ls(i,t)&&n.every(o=>i.every(s=>o.intersects(s,t)))))}test(e){if(!e)return!1;if(typeof e=="string")try{e=new qm(e,this.options)}catch{return!1}for(let t=0;t<this.set.length;t++)if(id(this.set[t],e,this.options))return!0;return!1}};Is.exports=rn;var Um=As(),Ps=new Um,jm=Pt(),nn=Ze(),I=Ke(),qm=W(),{safeRe:z,t:Y,comparatorTrimReplace:Gm,tildeTrimReplace:Vm,caretTrimReplace:Hm}=je(),{FLAG_INCLUDE_PRERELEASE:Wm,FLAG_LOOSE:Bm}=Ue(),Ts=r=>r.value==="<0.0.0-0",Ym=r=>r.value==="",Ls=(r,e)=>{let t=!0,n=r.slice(),i=n.pop();for(;t&&n.length;)t=n.every(o=>i.intersects(o,e)),i=n.pop();return t},Xm=(r,e)=>(r=r.replace(z[Y.BUILD],""),I("comp",r,e),r=Km(r,e),I("caret",r),r=zm(r,e),I("tildes",r),r=Zm(r,e),I("xrange",r),r=td(r,e),I("stars",r),r),J=r=>!r||r.toLowerCase()==="x"||r==="*",zm=(r,e)=>r.trim().split(/\s+/).map(t=>Jm(t,e)).join(" "),Jm=(r,e)=>{let t=e.loose?z[Y.TILDELOOSE]:z[Y.TILDE];return r.replace(t,(n,i,o,s,a)=>{I("tilde",r,n,i,o,s,a);let l;return J(i)?l="":J(o)?l=`>=${i}.0.0 <${+i+1}.0.0-0`:J(s)?l=`>=${i}.${o}.0 <${i}.${+o+1}.0-0`:a?(I("replaceTilde pr",a),l=`>=${i}.${o}.${s}-${a} <${i}.${+o+1}.0-0`):l=`>=${i}.${o}.${s} <${i}.${+o+1}.0-0`,I("tilde return",l),l})},Km=(r,e)=>r.trim().split(/\s+/).map(t=>Qm(t,e)).join(" "),Qm=(r,e)=>{I("caret",r,e);let t=e.loose?z[Y.CARETLOOSE]:z[Y.CARET],n=e.includePrerelease?"-0":"";return r.replace(t,(i,o,s,a,l)=>{I("caret",r,i,o,s,a,l);let u;return J(o)?u="":J(s)?u=`>=${o}.0.0${n} <${+o+1}.0.0-0`:J(a)?o==="0"?u=`>=${o}.${s}.0${n} <${o}.${+s+1}.0-0`:u=`>=${o}.${s}.0${n} <${+o+1}.0.0-0`:l?(I("replaceCaret pr",l),o==="0"?s==="0"?u=`>=${o}.${s}.${a}-${l} <${o}.${s}.${+a+1}-0`:u=`>=${o}.${s}.${a}-${l} <${o}.${+s+1}.0-0`:u=`>=${o}.${s}.${a}-${l} <${+o+1}.0.0-0`):(I("no pr"),o==="0"?s==="0"?u=`>=${o}.${s}.${a}${n} <${o}.${s}.${+a+1}-0`:u=`>=${o}.${s}.${a}${n} <${o}.${+s+1}.0-0`:u=`>=${o}.${s}.${a} <${+o+1}.0.0-0`),I("caret return",u),u})},Zm=(r,e)=>(I("replaceXRanges",r,e),r.split(/\s+/).map(t=>ed(t,e)).join(" ")),ed=(r,e)=>{r=r.trim();let t=e.loose?z[Y.XRANGELOOSE]:z[Y.XRANGE];return r.replace(t,(n,i,o,s,a,l)=>{I("xRange",r,n,i,o,s,a,l);let u=J(o),c=u||J(s),m=c||J(a),d=m;return i==="="&&d&&(i=""),l=e.includePrerelease?"-0":"",u?i===">"||i==="<"?n="<0.0.0-0":n="*":i&&d?(c&&(s=0),a=0,i===">"?(i=">=",c?(o=+o+1,s=0,a=0):(s=+s+1,a=0)):i==="<="&&(i="<",c?o=+o+1:s=+s+1),i==="<"&&(l="-0"),n=`${i+o}.${s}.${a}${l}`):c?n=`>=${o}.0.0${l} <${+o+1}.0.0-0`:m&&(n=`>=${o}.${s}.0${l} <${o}.${+s+1}.0-0`),I("xRange return",n),n})},td=(r,e)=>(I("replaceStars",r,e),r.trim().replace(z[Y.STAR],"")),rd=(r,e)=>(I("replaceGTE0",r,e),r.trim().replace(z[e.includePrerelease?Y.GTE0PRE:Y.GTE0],"")),nd=r=>(e,t,n,i,o,s,a,l,u,c,m,d)=>(J(n)?t="":J(i)?t=`>=${n}.0.0${r?"-0":""}`:J(o)?t=`>=${n}.${i}.0${r?"-0":""}`:s?t=`>=${t}`:t=`>=${t}${r?"-0":""}`,J(u)?l="":J(c)?l=`<${+u+1}.0.0-0`:J(m)?l=`<${u}.${+c+1}.0-0`:d?l=`<=${u}.${c}.${m}-${d}`:r?l=`<${u}.${c}.${+m+1}-0`:l=`<=${l}`,`${t} ${l}`.trim()),id=(r,e,t)=>{for(let n=0;n<r.length;n++)if(!r[n].test(e))return!1;if(e.prerelease.length&&!t.includePrerelease){for(let n=0;n<r.length;n++)if(I(r[n].semver),r[n].semver!==nn.ANY&&r[n].semver.prerelease.length>0){let i=r[n].semver;if(i.major===e.major&&i.minor===e.minor&&i.patch===e.patch)return!0}return!1}return!0}});var Ze=y((KE,js)=>{"use strict";var et=Symbol("SemVer ANY"),an=class r{static get ANY(){return et}constructor(e,t){if(t=Ms(t),e instanceof r){if(e.loose===!!t.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),sn("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===et?this.value="":this.value=this.operator+this.semver.version,sn("comp",this)}parse(e){let t=this.options.loose?Ns[Ds.COMPARATORLOOSE]:Ns[Ds.COMPARATOR],n=e.match(t);if(!n)throw new TypeError(`Invalid comparator: ${e}`);this.operator=n[1]!==void 0?n[1]:"",this.operator==="="&&(this.operator=""),n[2]?this.semver=new Fs(n[2],this.options.loose):this.semver=et}toString(){return this.value}test(e){if(sn("Comparator.test",e,this.options.loose),this.semver===et||e===et)return!0;if(typeof e=="string")try{e=new Fs(e,this.options)}catch{return!1}return on(e,this.operator,this.semver,this.options)}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new Us(e.value,t).test(this.value):e.operator===""?e.value===""?!0:new Us(this.value,t).test(e.semver):(t=Ms(t),t.includePrerelease&&(this.value==="<0.0.0-0"||e.value==="<0.0.0-0")||!t.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&e.operator.startsWith(">")||this.operator.startsWith("<")&&e.operator.startsWith("<")||this.semver.version===e.semver.version&&this.operator.includes("=")&&e.operator.includes("=")||on(this.semver,"<",e.semver,t)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||on(this.semver,">",e.semver,t)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};js.exports=an;var Ms=Pt(),{safeRe:Ns,t:Ds}=je(),on=en(),sn=Ke(),Fs=W(),Us=ne()});var tt=y((QE,qs)=>{"use strict";var od=ne(),sd=(r,e,t)=>{try{e=new od(e,t)}catch{return!1}return e.test(r)};qs.exports=sd});var Vs=y((ZE,Gs)=>{"use strict";var ad=ne(),ld=(r,e)=>new ad(r,e).set.map(t=>t.map(n=>n.value).join(" ").trim().split(" "));Gs.exports=ld});var Ws=y((e$,Hs)=>{"use strict";var cd=W(),ud=ne(),fd=(r,e,t)=>{let n=null,i=null,o=null;try{o=new ud(e,t)}catch{return null}return r.forEach(s=>{o.test(s)&&(!n||i.compare(s)===-1)&&(n=s,i=new cd(n,t))}),n};Hs.exports=fd});var Ys=y((t$,Bs)=>{"use strict";var md=W(),dd=ne(),pd=(r,e,t)=>{let n=null,i=null,o=null;try{o=new dd(e,t)}catch{return null}return r.forEach(s=>{o.test(s)&&(!n||i.compare(s)===1)&&(n=s,i=new md(n,t))}),n};Bs.exports=pd});var Js=y((r$,zs)=>{"use strict";var ln=W(),hd=ne(),Xs=Qe(),gd=(r,e)=>{r=new hd(r,e);let t=new ln("0.0.0");if(r.test(t)||(t=new ln("0.0.0-0"),r.test(t)))return t;t=null;for(let n=0;n<r.set.length;++n){let i=r.set[n],o=null;i.forEach(s=>{let a=new ln(s.semver.version);switch(s.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!o||Xs(a,o))&&(o=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${s.operator}`)}}),o&&(!t||Xs(t,o))&&(t=o)}return t&&r.test(t)?t:null};zs.exports=gd});var Qs=y((n$,Ks)=>{"use strict";var yd=ne(),wd=(r,e)=>{try{return new yd(r,e).range||"*"}catch{return null}};Ks.exports=wd});var Gt=y((i$,ra)=>{"use strict";var Ed=W(),ta=Ze(),{ANY:$d}=ta,bd=ne(),Rd=tt(),Zs=Qe(),ea=Dt(),Sd=Ut(),vd=Ft(),xd=(r,e,t,n)=>{r=new Ed(r,n),e=new bd(e,n);let i,o,s,a,l;switch(t){case">":i=Zs,o=Sd,s=ea,a=">",l=">=";break;case"<":i=ea,o=vd,s=Zs,a="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(Rd(r,e,n))return!1;for(let u=0;u<e.set.length;++u){let c=e.set[u],m=null,d=null;if(c.forEach(p=>{p.semver===$d&&(p=new ta(">=0.0.0")),m=m||p,d=d||p,i(p.semver,m.semver,n)?m=p:s(p.semver,d.semver,n)&&(d=p)}),m.operator===a||m.operator===l||(!d.operator||d.operator===a)&&o(r,d.semver))return!1;if(d.operator===l&&s(r,d.semver))return!1}return!0};ra.exports=xd});var ia=y((o$,na)=>{"use strict";var _d=Gt(),kd=(r,e,t)=>_d(r,e,">",t);na.exports=kd});var sa=y((s$,oa)=>{"use strict";var Od=Gt(),Cd=(r,e,t)=>Od(r,e,"<",t);oa.exports=Cd});var ca=y((a$,la)=>{"use strict";var aa=ne(),Ad=(r,e,t)=>(r=new aa(r,t),e=new aa(e,t),r.intersects(e,t));la.exports=Ad});var fa=y((l$,ua)=>{"use strict";var Pd=tt(),Td=re();ua.exports=(r,e,t)=>{let n=[],i=null,o=null,s=r.sort((c,m)=>Td(c,m,t));for(let c of s)Pd(c,e,t)?(o=c,i||(i=c)):(o&&n.push([i,o]),o=null,i=null);i&&n.push([i,null]);let a=[];for(let[c,m]of n)c===m?a.push(c):!m&&c===s[0]?a.push("*"):m?c===s[0]?a.push(`<=${m}`):a.push(`${c} - ${m}`):a.push(`>=${c}`);let l=a.join(" || "),u=typeof e.raw=="string"?e.raw:String(e);return l.length<u.length?l:e}});var ya=y((c$,ga)=>{"use strict";var ma=ne(),un=Ze(),{ANY:cn}=un,rt=tt(),fn=re(),Ld=(r,e,t={})=>{if(r===e)return!0;r=new ma(r,t),e=new ma(e,t);let n=!1;e:for(let i of r.set){for(let o of e.set){let s=Md(i,o,t);if(n=n||s!==null,s)continue e}if(n)return!1}return!0},Id=[new un(">=0.0.0-0")],da=[new un(">=0.0.0")],Md=(r,e,t)=>{if(r===e)return!0;if(r.length===1&&r[0].semver===cn){if(e.length===1&&e[0].semver===cn)return!0;t.includePrerelease?r=Id:r=da}if(e.length===1&&e[0].semver===cn){if(t.includePrerelease)return!0;e=da}let n=new Set,i,o;for(let p of r)p.operator===">"||p.operator===">="?i=pa(i,p,t):p.operator==="<"||p.operator==="<="?o=ha(o,p,t):n.add(p.semver);if(n.size>1)return null;let s;if(i&&o){if(s=fn(i.semver,o.semver,t),s>0)return null;if(s===0&&(i.operator!==">="||o.operator!=="<="))return null}for(let p of n){if(i&&!rt(p,String(i),t)||o&&!rt(p,String(o),t))return null;for(let w of e)if(!rt(p,String(w),t))return!1;return!0}let a,l,u,c,m=o&&!t.includePrerelease&&o.semver.prerelease.length?o.semver:!1,d=i&&!t.includePrerelease&&i.semver.prerelease.length?i.semver:!1;m&&m.prerelease.length===1&&o.operator==="<"&&m.prerelease[0]===0&&(m=!1);for(let p of e){if(c=c||p.operator===">"||p.operator===">=",u=u||p.operator==="<"||p.operator==="<=",i){if(d&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===d.major&&p.semver.minor===d.minor&&p.semver.patch===d.patch&&(d=!1),p.operator===">"||p.operator===">="){if(a=pa(i,p,t),a===p&&a!==i)return!1}else if(i.operator===">="&&!rt(i.semver,String(p),t))return!1}if(o){if(m&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===m.major&&p.semver.minor===m.minor&&p.semver.patch===m.patch&&(m=!1),p.operator==="<"||p.operator==="<="){if(l=ha(o,p,t),l===p&&l!==o)return!1}else if(o.operator==="<="&&!rt(o.semver,String(p),t))return!1}if(!p.operator&&(o||i)&&s!==0)return!1}return!(i&&u&&!o&&s!==0||o&&c&&!i&&s!==0||d||m)},pa=(r,e,t)=>{if(!r)return e;let n=fn(r.semver,e.semver,t);return n>0?r:n<0||e.operator===">"&&r.operator===">="?e:r},ha=(r,e,t)=>{if(!r)return e;let n=fn(r.semver,e.semver,t);return n<0?r:n>0||e.operator==="<"&&r.operator==="<="?e:r};ga.exports=Ld});var Vt=y((u$,$a)=>{"use strict";var mn=je(),wa=Ue(),Nd=W(),Ea=zr(),Dd=$e(),Fd=Vo(),Ud=Wo(),jd=Xo(),qd=Ko(),Gd=Zo(),Vd=ts(),Hd=ns(),Wd=os(),Bd=re(),Yd=cs(),Xd=fs(),zd=Nt(),Jd=hs(),Kd=ys(),Qd=Qe(),Zd=Dt(),ep=Qr(),tp=Zr(),rp=Ft(),np=Ut(),ip=en(),op=_s(),sp=Os(),ap=Ze(),lp=ne(),cp=tt(),up=Vs(),fp=Ws(),mp=Ys(),dp=Js(),pp=Qs(),hp=Gt(),gp=ia(),yp=sa(),wp=ca(),Ep=fa(),$p=ya();$a.exports={parse:Dd,valid:Fd,clean:Ud,inc:jd,diff:qd,major:Gd,minor:Vd,patch:Hd,prerelease:Wd,compare:Bd,rcompare:Yd,compareLoose:Xd,compareBuild:zd,sort:Jd,rsort:Kd,gt:Qd,lt:Zd,eq:ep,neq:tp,gte:rp,lte:np,cmp:ip,coerce:op,truncate:sp,Comparator:ap,Range:lp,satisfies:cp,toComparators:up,maxSatisfying:fp,minSatisfying:mp,minVersion:dp,validRange:pp,outside:hp,gtr:gp,ltr:yp,intersects:wp,simplifyRange:Ep,subset:$p,SemVer:Nd,re:mn.re,src:mn.src,tokens:mn.t,SEMVER_SPEC_VERSION:wa.SEMVER_SPEC_VERSION,RELEASE_TYPES:wa.RELEASE_TYPES,compareIdentifiers:Ea.compareIdentifiers,rcompareIdentifiers:Ea.rcompareIdentifiers}});var Ra=y((f$,ba)=>{var bp=Vt();ba.exports=bp.satisfies(process.version,">=15.7.0")});var va=y((m$,Sa)=>{var Rp=Vt();Sa.exports=Rp.satisfies(process.version,">=16.9.0")});var dn=y((d$,xa)=>{var Sp=Ra(),vp=va(),xp={ec:["ES256","ES384","ES512"],rsa:["RS256","PS256","RS384","PS384","RS512","PS512"],"rsa-pss":["PS256","PS384","PS512"]},_p={ES256:"prime256v1",ES384:"secp384r1",ES512:"secp521r1"};xa.exports=function(r,e){if(!r||!e)return;let t=e.asymmetricKeyType;if(!t)return;let n=xp[t];if(!n)throw new Error(`Unknown key type "${t}".`);if(!n.includes(r))throw new Error(`"alg" parameter for "${t}" key type must be one of: ${n.join(", ")}.`);if(Sp)switch(t){case"ec":let i=e.asymmetricKeyDetails.namedCurve,o=_p[r];if(i!==o)throw new Error(`"alg" parameter "${r}" requires curve "${o}".`);break;case"rsa-pss":if(vp){let s=parseInt(r.slice(-3),10),{hashAlgorithm:a,mgf1HashAlgorithm:l,saltLength:u}=e.asymmetricKeyDetails;if(a!==`sha${s}`||l!==a)throw new Error(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${r}.`);if(u!==void 0&&u>s>>3)throw new Error(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${r}.`)}break}}});var pn=y((p$,_a)=>{var kp=Vt();_a.exports=kp.satisfies(process.version,"^6.12.0 || >=8.0.0")});var Ca=y((h$,Oa)=>{var L=Je(),Op=Hr(),ka=Wr(),Cp=Vr(),Ap=Br(),Pp=dn(),Tp=pn(),Lp=_t(),{KeyObject:Ip,createSecretKey:Mp,createPublicKey:Np}=require("crypto"),hn=["RS256","RS384","RS512"],Dp=["ES256","ES384","ES512"],gn=["RS256","RS384","RS512"],Fp=["HS256","HS384","HS512"];Tp&&(hn.splice(hn.length,0,"PS256","PS384","PS512"),gn.splice(gn.length,0,"PS256","PS384","PS512"));Oa.exports=function(r,e,t,n){typeof t=="function"&&!n&&(n=t,t={}),t||(t={}),t=Object.assign({},t);let i;if(n?i=n:i=function(c,m){if(c)throw c;return m},t.clockTimestamp&&typeof t.clockTimestamp!="number")return i(new L("clockTimestamp must be a number"));if(t.nonce!==void 0&&(typeof t.nonce!="string"||t.nonce.trim()===""))return i(new L("nonce must be a non-empty string"));if(t.allowInvalidAsymmetricKeyTypes!==void 0&&typeof t.allowInvalidAsymmetricKeyTypes!="boolean")return i(new L("allowInvalidAsymmetricKeyTypes must be a boolean"));let o=t.clockTimestamp||Math.floor(Date.now()/1e3);if(!r)return i(new L("jwt must be provided"));if(typeof r!="string")return i(new L("jwt must be a string"));let s=r.split(".");if(s.length!==3)return i(new L("jwt malformed"));let a;try{a=Cp(r,{complete:!0})}catch(c){return i(c)}if(!a)return i(new L("invalid token"));let l=a.header,u;if(typeof e=="function"){if(!n)return i(new L("verify must be called asynchronous if secret or public key is provided as a callback"));u=e}else u=function(c,m){return m(null,e)};return u(l,function(c,m){if(c)return i(new L("error in secret or public key callback: "+c.message));let d=s[2].trim()!=="";if(!d&&m)return i(new L("jwt signature is required"));if(d&&!m)return i(new L("secret or public key must be provided"));if(!d&&!t.algorithms)return i(new L('please specify "none" in "algorithms" to verify unsigned tokens'));if(m!=null&&!(m instanceof Ip))try{m=Np(m)}catch{try{m=Mp(typeof m=="string"?Buffer.from(m):m)}catch{return i(new L("secretOrPublicKey is not valid key material"))}}if(t.algorithms||(m.type==="secret"?t.algorithms=Fp:["rsa","rsa-pss"].includes(m.asymmetricKeyType)?t.algorithms=gn:m.asymmetricKeyType==="ec"?t.algorithms=Dp:t.algorithms=hn),t.algorithms.indexOf(a.header.alg)===-1)return i(new L("invalid algorithm"));if(l.alg.startsWith("HS")&&m.type!=="secret")return i(new L(`secretOrPublicKey must be a symmetric key when using ${l.alg}`));if(/^(?:RS|PS|ES)/.test(l.alg)&&m.type!=="public")return i(new L(`secretOrPublicKey must be an asymmetric key when using ${l.alg}`));if(!t.allowInvalidAsymmetricKeyTypes)try{Pp(l.alg,m)}catch(v){return i(v)}let p;try{p=Lp.verify(r,a.header.alg,m)}catch(v){return i(v)}if(!p)return i(new L("invalid signature"));let w=a.payload;if(typeof w.nbf<"u"&&!t.ignoreNotBefore){if(typeof w.nbf!="number")return i(new L("invalid nbf value"));if(w.nbf>o+(t.clockTolerance||0))return i(new Op("jwt not active",new Date(w.nbf*1e3)))}if(typeof w.exp<"u"&&!t.ignoreExpiration){if(typeof w.exp!="number")return i(new L("invalid exp value"));if(o>=w.exp+(t.clockTolerance||0))return i(new ka("jwt expired",new Date(w.exp*1e3)))}if(t.audience){let v=Array.isArray(t.audience)?t.audience:[t.audience];if(!(Array.isArray(w.aud)?w.aud:[w.aud]).some(function(b){return v.some(function(R){return R instanceof RegExp?R.test(b):R===b})}))return i(new L("jwt audience invalid. expected: "+v.join(" or ")))}if(t.issuer&&(typeof t.issuer=="string"&&w.iss!==t.issuer||Array.isArray(t.issuer)&&t.issuer.indexOf(w.iss)===-1))return i(new L("jwt issuer invalid. expected: "+t.issuer));if(t.subject&&w.sub!==t.subject)return i(new L("jwt subject invalid. expected: "+t.subject));if(t.jwtid&&w.jti!==t.jwtid)return i(new L("jwt jwtid invalid. expected: "+t.jwtid));if(t.nonce&&w.nonce!==t.nonce)return i(new L("jwt nonce invalid. expected: "+t.nonce));if(t.maxAge){if(typeof w.iat!="number")return i(new L("iat required when maxAge is specified"));let v=Ap(t.maxAge,w.iat);if(typeof v>"u")return i(new L('"maxAge" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'));if(o>=v+(t.clockTolerance||0))return i(new ka("maxAge exceeded",new Date(v*1e3)))}if(t.complete===!0){let v=a.signature;return i(null,{header:l,payload:w,signature:v})}return i(null,w)})}});var Ma=y((g$,Ia)=>{var Aa=1/0,Ta=9007199254740991,Up=17976931348623157e292,Pa=NaN,jp="[object Arguments]",qp="[object Function]",Gp="[object GeneratorFunction]",Vp="[object String]",Hp="[object Symbol]",Wp=/^\s+|\s+$/g,Bp=/^[-+]0x[0-9a-f]+$/i,Yp=/^0b[01]+$/i,Xp=/^0o[0-7]+$/i,zp=/^(?:0|[1-9]\d*)$/,Jp=parseInt;function Kp(r,e){for(var t=-1,n=r?r.length:0,i=Array(n);++t<n;)i[t]=e(r[t],t,r);return i}function Qp(r,e,t,n){for(var i=r.length,o=t+(n?1:-1);n?o--:++o<i;)if(e(r[o],o,r))return o;return-1}function Zp(r,e,t){if(e!==e)return Qp(r,eh,t);for(var n=t-1,i=r.length;++n<i;)if(r[n]===e)return n;return-1}function eh(r){return r!==r}function th(r,e){for(var t=-1,n=Array(r);++t<r;)n[t]=e(t);return n}function rh(r,e){return Kp(e,function(t){return r[t]})}function nh(r,e){return function(t){return r(e(t))}}var Ht=Object.prototype,wn=Ht.hasOwnProperty,Wt=Ht.toString,ih=Ht.propertyIsEnumerable,oh=nh(Object.keys,Object),sh=Math.max;function ah(r,e){var t=La(r)||mh(r)?th(r.length,String):[],n=t.length,i=!!n;for(var o in r)(e||wn.call(r,o))&&!(i&&(o=="length"||ch(o,n)))&&t.push(o);return t}function lh(r){if(!uh(r))return oh(r);var e=[];for(var t in Object(r))wn.call(r,t)&&t!="constructor"&&e.push(t);return e}function ch(r,e){return e=e??Ta,!!e&&(typeof r=="number"||zp.test(r))&&r>-1&&r%1==0&&r<e}function uh(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||Ht;return r===t}function fh(r,e,t,n){r=En(r)?r:Rh(r),t=t&&!n?Eh(t):0;var i=r.length;return t<0&&(t=sh(i+t,0)),gh(r)?t<=i&&r.indexOf(e,t)>-1:!!i&&Zp(r,e,t)>-1}function mh(r){return dh(r)&&wn.call(r,"callee")&&(!ih.call(r,"callee")||Wt.call(r)==jp)}var La=Array.isArray;function En(r){return r!=null&&hh(r.length)&&!ph(r)}function dh(r){return $n(r)&&En(r)}function ph(r){var e=yn(r)?Wt.call(r):"";return e==qp||e==Gp}function hh(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=Ta}function yn(r){var e=typeof r;return!!r&&(e=="object"||e=="function")}function $n(r){return!!r&&typeof r=="object"}function gh(r){return typeof r=="string"||!La(r)&&$n(r)&&Wt.call(r)==Vp}function yh(r){return typeof r=="symbol"||$n(r)&&Wt.call(r)==Hp}function wh(r){if(!r)return r===0?r:0;if(r=$h(r),r===Aa||r===-Aa){var e=r<0?-1:1;return e*Up}return r===r?r:0}function Eh(r){var e=wh(r),t=e%1;return e===e?t?e-t:e:0}function $h(r){if(typeof r=="number")return r;if(yh(r))return Pa;if(yn(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=yn(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=r.replace(Wp,"");var t=Yp.test(r);return t||Xp.test(r)?Jp(r.slice(2),t?2:8):Bp.test(r)?Pa:+r}function bh(r){return En(r)?ah(r):lh(r)}function Rh(r){return r?rh(r,bh(r)):[]}Ia.exports=fh});var Da=y((y$,Na)=>{var Sh="[object Boolean]",vh=Object.prototype,xh=vh.toString;function _h(r){return r===!0||r===!1||kh(r)&&xh.call(r)==Sh}function kh(r){return!!r&&typeof r=="object"}Na.exports=_h});var Ga=y((w$,qa)=>{var Fa=1/0,Oh=17976931348623157e292,Ua=NaN,Ch="[object Symbol]",Ah=/^\s+|\s+$/g,Ph=/^[-+]0x[0-9a-f]+$/i,Th=/^0b[01]+$/i,Lh=/^0o[0-7]+$/i,Ih=parseInt,Mh=Object.prototype,Nh=Mh.toString;function Dh(r){return typeof r=="number"&&r==qh(r)}function ja(r){var e=typeof r;return!!r&&(e=="object"||e=="function")}function Fh(r){return!!r&&typeof r=="object"}function Uh(r){return typeof r=="symbol"||Fh(r)&&Nh.call(r)==Ch}function jh(r){if(!r)return r===0?r:0;if(r=Gh(r),r===Fa||r===-Fa){var e=r<0?-1:1;return e*Oh}return r===r?r:0}function qh(r){var e=jh(r),t=e%1;return e===e?t?e-t:e:0}function Gh(r){if(typeof r=="number")return r;if(Uh(r))return Ua;if(ja(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=ja(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=r.replace(Ah,"");var t=Th.test(r);return t||Lh.test(r)?Ih(r.slice(2),t?2:8):Ph.test(r)?Ua:+r}qa.exports=Dh});var Ha=y((E$,Va)=>{var Vh="[object Number]",Hh=Object.prototype,Wh=Hh.toString;function Bh(r){return!!r&&typeof r=="object"}function Yh(r){return typeof r=="number"||Bh(r)&&Wh.call(r)==Vh}Va.exports=Yh});var Xa=y(($$,Ya)=>{var Xh="[object Object]";function zh(r){var e=!1;if(r!=null&&typeof r.toString!="function")try{e=!!(r+"")}catch{}return e}function Jh(r,e){return function(t){return r(e(t))}}var Kh=Function.prototype,Wa=Object.prototype,Ba=Kh.toString,Qh=Wa.hasOwnProperty,Zh=Ba.call(Object),eg=Wa.toString,tg=Jh(Object.getPrototypeOf,Object);function rg(r){return!!r&&typeof r=="object"}function ng(r){if(!rg(r)||eg.call(r)!=Xh||zh(r))return!1;var e=tg(r);if(e===null)return!0;var t=Qh.call(e,"constructor")&&e.constructor;return typeof t=="function"&&t instanceof t&&Ba.call(t)==Zh}Ya.exports=ng});var Ja=y((b$,za)=>{var ig="[object String]",og=Object.prototype,sg=og.toString,ag=Array.isArray;function lg(r){return!!r&&typeof r=="object"}function cg(r){return typeof r=="string"||!ag(r)&&lg(r)&&sg.call(r)==ig}za.exports=cg});var tl=y((R$,el)=>{var ug="Expected a function",Ka=1/0,fg=17976931348623157e292,Qa=NaN,mg="[object Symbol]",dg=/^\s+|\s+$/g,pg=/^[-+]0x[0-9a-f]+$/i,hg=/^0b[01]+$/i,gg=/^0o[0-7]+$/i,yg=parseInt,wg=Object.prototype,Eg=wg.toString;function $g(r,e){var t;if(typeof e!="function")throw new TypeError(ug);return r=xg(r),function(){return--r>0&&(t=e.apply(this,arguments)),r<=1&&(e=void 0),t}}function bg(r){return $g(2,r)}function Za(r){var e=typeof r;return!!r&&(e=="object"||e=="function")}function Rg(r){return!!r&&typeof r=="object"}function Sg(r){return typeof r=="symbol"||Rg(r)&&Eg.call(r)==mg}function vg(r){if(!r)return r===0?r:0;if(r=_g(r),r===Ka||r===-Ka){var e=r<0?-1:1;return e*fg}return r===r?r:0}function xg(r){var e=vg(r),t=e%1;return e===e?t?e-t:e:0}function _g(r){if(typeof r=="number")return r;if(Sg(r))return Qa;if(Za(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=Za(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=r.replace(dg,"");var t=hg.test(r);return t||gg.test(r)?yg(r.slice(2),t?2:8):pg.test(r)?Qa:+r}el.exports=bg});var ul=y((S$,cl)=>{var rl=Br(),kg=pn(),Og=dn(),nl=_t(),Cg=Ma(),Bt=Da(),il=Ga(),bn=Ha(),sl=Xa(),be=Ja(),Ag=tl(),{KeyObject:Pg,createSecretKey:Tg,createPrivateKey:Lg}=require("crypto"),al=["RS256","RS384","RS512","ES256","ES384","ES512","HS256","HS384","HS512","none"];kg&&al.splice(3,0,"PS256","PS384","PS512");var Ig={expiresIn:{isValid:function(r){return il(r)||be(r)&&r},message:'"expiresIn" should be a number of seconds or string representing a timespan'},notBefore:{isValid:function(r){return il(r)||be(r)&&r},message:'"notBefore" should be a number of seconds or string representing a timespan'},audience:{isValid:function(r){return be(r)||Array.isArray(r)},message:'"audience" must be a string or array'},algorithm:{isValid:Cg.bind(null,al),message:'"algorithm" must be a valid string enum value'},header:{isValid:sl,message:'"header" must be an object'},encoding:{isValid:be,message:'"encoding" must be a string'},issuer:{isValid:be,message:'"issuer" must be a string'},subject:{isValid:be,message:'"subject" must be a string'},jwtid:{isValid:be,message:'"jwtid" must be a string'},noTimestamp:{isValid:Bt,message:'"noTimestamp" must be a boolean'},keyid:{isValid:be,message:'"keyid" must be a string'},mutatePayload:{isValid:Bt,message:'"mutatePayload" must be a boolean'},allowInsecureKeySizes:{isValid:Bt,message:'"allowInsecureKeySizes" must be a boolean'},allowInvalidAsymmetricKeyTypes:{isValid:Bt,message:'"allowInvalidAsymmetricKeyTypes" must be a boolean'}},Mg={iat:{isValid:bn,message:'"iat" should be a number of seconds'},exp:{isValid:bn,message:'"exp" should be a number of seconds'},nbf:{isValid:bn,message:'"nbf" should be a number of seconds'}};function ll(r,e,t,n){if(!sl(t))throw new Error('Expected "'+n+'" to be a plain object.');Object.keys(t).forEach(function(i){let o=r[i];if(!o){if(!e)throw new Error('"'+i+'" is not allowed in "'+n+'"');return}if(!o.isValid(t[i]))throw new Error(o.message)})}function Ng(r){return ll(Ig,!1,r,"options")}function Dg(r){return ll(Mg,!0,r,"payload")}var ol={audience:"aud",issuer:"iss",subject:"sub",jwtid:"jti"},Fg=["expiresIn","notBefore","noTimestamp","audience","issuer","subject","jwtid"];cl.exports=function(r,e,t,n){typeof t=="function"?(n=t,t={}):t=t||{};let i=typeof r=="object"&&!Buffer.isBuffer(r),o=Object.assign({alg:t.algorithm||"HS256",typ:i?"JWT":void 0,kid:t.keyid},t.header);function s(u){if(n)return n(u);throw u}if(!e&&t.algorithm!=="none")return s(new Error("secretOrPrivateKey must have a value"));if(e!=null&&!(e instanceof Pg))try{e=Lg(e)}catch{try{e=Tg(typeof e=="string"?Buffer.from(e):e)}catch{return s(new Error("secretOrPrivateKey is not valid key material"))}}if(o.alg.startsWith("HS")&&e.type!=="secret")return s(new Error(`secretOrPrivateKey must be a symmetric key when using ${o.alg}`));if(/^(?:RS|PS|ES)/.test(o.alg)){if(e.type!=="private")return s(new Error(`secretOrPrivateKey must be an asymmetric key when using ${o.alg}`));if(!t.allowInsecureKeySizes&&!o.alg.startsWith("ES")&&e.asymmetricKeyDetails!==void 0&&e.asymmetricKeyDetails.modulusLength<2048)return s(new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${o.alg}`))}if(typeof r>"u")return s(new Error("payload is required"));if(i){try{Dg(r)}catch(u){return s(u)}t.mutatePayload||(r=Object.assign({},r))}else{let u=Fg.filter(function(c){return typeof t[c]<"u"});if(u.length>0)return s(new Error("invalid "+u.join(",")+" option for "+typeof r+" payload"))}if(typeof r.exp<"u"&&typeof t.expiresIn<"u")return s(new Error('Bad "options.expiresIn" option the payload already has an "exp" property.'));if(typeof r.nbf<"u"&&typeof t.notBefore<"u")return s(new Error('Bad "options.notBefore" option the payload already has an "nbf" property.'));try{Ng(t)}catch(u){return s(u)}if(!t.allowInvalidAsymmetricKeyTypes)try{Og(o.alg,e)}catch(u){return s(u)}let a=r.iat||Math.floor(Date.now()/1e3);if(t.noTimestamp?delete r.iat:i&&(r.iat=a),typeof t.notBefore<"u"){try{r.nbf=rl(t.notBefore,a)}catch(u){return s(u)}if(typeof r.nbf>"u")return s(new Error('"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'))}if(typeof t.expiresIn<"u"&&typeof r=="object"){try{r.exp=rl(t.expiresIn,a)}catch(u){return s(u)}if(typeof r.exp>"u")return s(new Error('"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'))}Object.keys(ol).forEach(function(u){let c=ol[u];if(typeof t[u]<"u"){if(typeof r[c]<"u")return s(new Error('Bad "options.'+u+'" option. The payload already has an "'+c+'" property.'));r[c]=t[u]}});let l=t.encoding||"utf8";if(typeof n=="function")n=n&&Ag(n),nl.createSign({header:o,privateKey:e,payload:r,encoding:l}).once("error",n).once("done",function(u){if(!t.allowInsecureKeySizes&&/^(?:RS|PS)/.test(o.alg)&&u.length<256)return n(new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${o.alg}`));n(null,u)});else{let u=nl.sign({header:o,payload:r,secret:e,encoding:l});if(!t.allowInsecureKeySizes&&/^(?:RS|PS)/.test(o.alg)&&u.length<256)throw new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${o.alg}`);return u}}});var Rn=y((v$,fl)=>{fl.exports={decode:Vr(),verify:Ca(),sign:ul(),JsonWebTokenError:Je(),NotBeforeError:Hr(),TokenExpiredError:Wr()}});var ql=y((ub,jl)=>{function Ll(r){return Array.isArray(r)?r:[r]}var Dn="",Il=" ",Mn="\\",by=/^\s+$/,Ry=/(?:[^\\]|^)\\$/,Sy=/^\\!/,vy=/^\\#/,xy=/\r?\n/g,_y=/^\.*\/|^\.+$/,Nn="/",Dl="node-ignore";typeof Symbol<"u"&&(Dl=Symbol.for("node-ignore"));var Ml=Dl,ky=(r,e,t)=>Object.defineProperty(r,e,{value:t}),Oy=/([0-z])-([0-z])/g,Fl=()=>!1,Cy=r=>r.replace(Oy,(e,t,n)=>t.charCodeAt(0)<=n.charCodeAt(0)?e:Dn),Ay=r=>{let{length:e}=r;return r.slice(0,e-e%2)},Py=[[/^\uFEFF/,()=>Dn],[/((?:\\\\)*?)(\\?\s+)$/,(r,e,t)=>e+(t.indexOf("\\")===0?Il:Dn)],[/(\\+?)\s/g,(r,e)=>{let{length:t}=e;return e.slice(0,t-t%2)+Il}],[/[\\$.|*+(){^]/g,r=>`\\${r}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(r,e,t)=>e+6<t.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(r,e,t)=>{let n=t.replace(/\\\*/g,"[^\\/]*");return e+n}],[/\\\\\\(?=[$.|*+(){^])/g,()=>Mn],[/\\\\/g,()=>Mn],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(r,e,t,n,i)=>e===Mn?`\\[${t}${Ay(n)}${i}`:i==="]"&&n.length%2===0?`[${Cy(t)}${n}]`:"[]"],[/(?:[^*])$/,r=>/\/$/.test(r)?`${r}$`:`${r}(?=$|\\/$)`],[/(\^|\\\/)?\\\*$/,(r,e)=>`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`]],Nl=Object.create(null),Ty=(r,e)=>{let t=Nl[r];return t||(t=Py.reduce((n,[i,o])=>n.replace(i,o.bind(r)),r),Nl[r]=t),e?new RegExp(t,"i"):new RegExp(t)},jn=r=>typeof r=="string",Ly=r=>r&&jn(r)&&!by.test(r)&&!Ry.test(r)&&r.indexOf("#")!==0,Iy=r=>r.split(xy),Fn=class{constructor(e,t,n,i){this.origin=e,this.pattern=t,this.negative=n,this.regex=i}},My=(r,e)=>{let t=r,n=!1;r.indexOf("!")===0&&(n=!0,r=r.substr(1)),r=r.replace(Sy,"!").replace(vy,"#");let i=Ty(r,e);return new Fn(t,r,n,i)},Ny=(r,e)=>{throw new e(r)},ye=(r,e,t)=>jn(r)?r?ye.isNotRelative(r)?t(`path should be a \`path.relative()\`d string, but got "${e}"`,RangeError):!0:t("path must not be empty",TypeError):t(`path must be a string, but got \`${e}\``,TypeError),Ul=r=>_y.test(r);ye.isNotRelative=Ul;ye.convert=r=>r;var Un=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:n=!1}={}){ky(this,Ml,!0),this._rules=[],this._ignoreCase=t,this._allowRelativePaths=n,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}_addPattern(e){if(e&&e[Ml]){this._rules=this._rules.concat(e._rules),this._added=!0;return}if(Ly(e)){let t=My(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,Ll(jn(e)?Iy(e):e).forEach(this._addPattern,this),this._added&&this._initCache(),this}addPattern(e){return this.add(e)}_testOne(e,t){let n=!1,i=!1;return this._rules.forEach(o=>{let{negative:s}=o;if(i===s&&n!==i||s&&!n&&!i&&!t)return;o.regex.test(e)&&(n=!s,i=s)}),{ignored:n,unignored:i}}_test(e,t,n,i){let o=e&&ye.convert(e);return ye(o,e,this._allowRelativePaths?Fl:Ny),this._t(o,t,n,i)}_t(e,t,n,i){if(e in t)return t[e];if(i||(i=e.split(Nn)),i.pop(),!i.length)return t[e]=this._testOne(e,n);let o=this._t(i.join(Nn)+Nn,t,n,i);return t[e]=o.ignored?o:this._testOne(e,n)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return Ll(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},er=r=>new Un(r),Dy=r=>ye(r&&ye.convert(r),r,Fl);er.isPathValid=Dy;er.default=er;jl.exports=er;if(typeof process<"u"&&(process.env&&process.env.IGNORE_TEST_WIN32||process.platform==="win32")){let r=t=>/^\\\\\?\\/.test(t)||/["<>|\u0000-\u001F]+/u.test(t)?t:t.replace(/\\/g,"/");ye.convert=r;let e=/^[a-z]:\//i;ye.isNotRelative=t=>e.test(t)||Ul(t)}});(function(){wi().config(Object.assign({},$i(),Ri()(process.argv)))})();var qc=require("fs"),Gc=require("path");var Uc=O(gt());var ae=O(require("fs")),On=O(require("path")),gl=O(require("os")),yl=O(Rn());var Ug=process.stdout.isTTY===!0&&!process.env.NO_COLOR,Re=r=>Ug?r:"",S=Re("\x1B[32m"),C=Re("\x1B[33m"),_=Re("\x1B[36m"),ie=Re("\x1B[35m"),h=Re("\x1B[31m"),g=Re("\x1B[2m"),K=Re("\x1B[1m"),f=Re("\x1B[0m");var ml="app.boxel.realms";var jg={"anthropic/claude-3.5-sonnet":"Anthropic: Claude 3.5 Sonnet","anthropic/claude-3.7-sonnet":"Anthropic: Claude 3.7 Sonnet","anthropic/claude-3.7-sonnet:thinking":"Anthropic: Claude 3.7 Sonnet (thinking)","anthropic/claude-haiku-4.5":"Anthropic: Claude Haiku 4.5","anthropic/claude-sonnet-4":"Anthropic: Claude Sonnet 4","anthropic/claude-sonnet-4.5":"Anthropic: Claude Sonnet 4.5","anthropic/claude-sonnet-4.6":"Anthropic: Claude Sonnet 4.6","anthropic/claude-opus-4.1":"Anthropic: Claude Opus 4.1","deepseek/deepseek-chat-v3-0324":"DeepSeek: DeepSeek V3 0324","google/gemini-2.5-pro":"Google: Gemini 2.5 Pro","google/gemini-2.5-flash-lite":"Google: Gemini 2.5 Flash Lite","google/gemini-2.5-flash":"Google: Gemini 2.5 Flash","meta-llama/llama-3.2-3b-instruct":"Meta: Llama 3.2 3B Instruct","openai/gpt-4.1-nano":"OpenAI: GPT-4.1 Nano","openai/gpt-4.1-mini":"OpenAI: GPT-4.1 Mini","openai/gpt-4.1":"OpenAI: GPT-4.1","openai/gpt-4o":"OpenAI: GPT-4o","openai/gpt-4o-mini":"OpenAI: GPT-4o-mini","openai/gpt-5-nano":"OpenAI: GPT-5 Nano","openai/gpt-5-mini":"OpenAI: GPT-5 Mini","openai/gpt-5":"OpenAI: GPT-5","openai/gpt-oss-20b":"OpenAI: GPT OSS 20B"},_$=Object.keys(jg);function P(r){return r.endsWith("/")?r:`${r}/`}async function dl(r,e,t){let n=await fetch(new URL("_matrix/client/v3/login",r).href,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({identifier:{type:"m.id.user",user:e},password:t,type:"m.login.password"})}),i=await n.json();if(!n.ok)throw new Error(`Matrix login failed: ${n.status} ${JSON.stringify(i)}`);return{accessToken:i.access_token,deviceId:i.device_id,userId:i.user_id,matrixUrl:r}}async function qg(r){let e=await fetch(new URL(`_matrix/client/v3/user/${encodeURIComponent(r.userId)}/openid/request_token`,r.matrixUrl).href,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r.accessToken}`},body:"{}"});if(!e.ok){let t=await e.text();throw new Error(`OpenID token request failed: ${e.status} ${t}`)}return await e.json()}async function Sn(r,e){let t=await qg(r),n=`${e.replace(/\/$/,"")}/_server-session`,i=await fetch(n,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(t)});if(!i.ok){let s=await i.text();throw new Error(`Realm server session failed: ${i.status} ${s}`)}let o=i.headers.get("Authorization");if(!o)throw new Error("Realm server session response did not include an Authorization header");return o}async function vn(r,e){let t=`${r.replace(/\/$/,"")}/_realm-auth`,n=await fetch(t,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:e}});if(!n.ok){let i=await n.text();throw new Error(`Realm auth lookup failed: ${n.status} ${i}`)}return await n.json()}function xn(r){return new URL(`_matrix/client/v3/user/${encodeURIComponent(r.userId)}/account_data/${ml}`,r.matrixUrl).href}async function Yt(r){try{let e=await fetch(xn(r),{headers:{Authorization:`Bearer ${r.accessToken}`}});if(!e.ok)return[];let t=await e.json();return Array.isArray(t.realms)?[...t.realms]:[]}catch{return[]}}async function pl(r,e){let t=await Yt(r);if(!t.includes(e)){t.push(e);let n=await fetch(xn(r),{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r.accessToken}`},body:JSON.stringify({realms:t})});if(!n.ok){let i=await n.text();throw new Error(`Failed to update Matrix account data: ${n.status} ${i}`)}}}async function hl(r,e){let t=P(e),n=await Yt(r),i=n.filter(s=>P(s)!==t);if(i.length===n.length)return!1;let o=await fetch(xn(r),{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r.accessToken}`},body:JSON.stringify({realms:i})});if(!o.ok){let s=await o.text();throw new Error(`Failed to update Matrix account data: ${o.status} ${s}`)}return!0}var Gg=On.join(gl.homedir(),".boxel-cli"),Vg="profiles.json",Hg=86400;function Wg(r,e=Hg){let t=r.replace(/^Bearer\s+/i,""),n=yl.default.decode(t);if(!n?.exp)return!0;let i=Math.floor(Date.now()/1e3);return n.exp-i<e}var M="No active profile. Run `boxel profile add` to create one.";function Xt(r){return r.endsWith(":stack.cards")?"staging":r.endsWith(":boxel.ai")?"production":r.endsWith(":localhost")?"local":"unknown"}function qe(r){let e=r.match(/^@([^:]+):/);return e?e[1]:r}function zt(r){let e=r.match(/:([^:]+)$/);return e?e[1]:"unknown"}function fe(r){let e=qe(r),t=zt(r);return`${g}[${f}${_}${e}${f} ${g}\xB7${f} ${ie}${t}${f}${g}]${f}`}var kn=class{config;configDir;profilesFile;constructor(e){this.configDir=e||Gg,this.profilesFile=On.join(this.configDir,Vg),this.config=this.loadConfig()}ensureConfigDir(){ae.existsSync(this.configDir)||ae.mkdirSync(this.configDir,{recursive:!0})}loadConfig(){let e={profiles:{},activeProfile:null};if(ae.existsSync(this.profilesFile))try{let t=ae.readFileSync(this.profilesFile,"utf-8"),n=JSON.parse(t);if(n&&typeof n=="object"&&!Array.isArray(n)){let i=n,o=i.profiles&&typeof i.profiles=="object"&&!Array.isArray(i.profiles)?i.profiles:null,s=i.activeProfile===null||typeof i.activeProfile=="string"?i.activeProfile:null;if(o)return{profiles:o,activeProfile:s}}}catch{}return e}saveConfig(){this.ensureConfigDir(),ae.writeFileSync(this.profilesFile,JSON.stringify(this.config,null,2),{mode:384});try{ae.chmodSync(this.profilesFile,384)}catch{}}listProfiles(){return Object.keys(this.config.profiles)}getProfile(e){return this.config.profiles[e]}getActiveProfileId(){return this.config.activeProfile}getActiveProfile(){let e=this.config.activeProfile;if(!e)return null;let t=this.config.profiles[e];return t?{id:e,profile:t}:null}async addProfile(e,t,n,i,o){let s=Xt(e),a=qe(e);if(s==="unknown"&&(!i||!o))throw new Error(`Unknown domain in Matrix ID "${e}". You must provide explicit --matrix-url and --realm-server-url for non-standard domains.`);let l=s==="production"?"https://matrix.boxel.ai":"https://matrix-staging.stack.cards",u=s==="production"?"https://app.boxel.ai/":"https://realms-staging.stack.cards/",c=zt(e),m={displayName:n||`${a} \xB7 ${c}`,matrixUrl:i||l,realmServerUrl:o||u,password:t};this.config.profiles[e]=m,this.config.activeProfile||(this.config.activeProfile=e),this.saveConfig()}async removeProfile(e){if(!this.config.profiles[e])return!1;if(delete this.config.profiles[e],this.config.activeProfile===e){let t=Object.keys(this.config.profiles);this.config.activeProfile=t.length>0?t[0]:null}return this.saveConfig(),!0}switchProfile(e){return this.config.profiles[e]?(this.config.activeProfile=e,this.saveConfig(),!0):!1}async getActiveCredentials(){let e=this.getActiveProfile();if(e&&e.profile.password)return{matrixUrl:e.profile.matrixUrl,username:qe(e.id),password:e.profile.password,realmServerUrl:e.profile.realmServerUrl,profileId:e.id};let t=process.env.MATRIX_URL,n=process.env.MATRIX_USERNAME,i=process.env.MATRIX_PASSWORD,o=process.env.REALM_SERVER_URL;return t&&n&&i&&o?{matrixUrl:t,username:n,password:i,realmServerUrl:o,profileId:null}:null}async getPassword(e){return this.config.profiles[e]?.password||null}async updatePassword(e,t){return this.config.profiles[e]?(this.config.profiles[e].password=t,this.saveConfig(),!0):!1}updateDisplayName(e,t){return this.config.profiles[e]?(this.config.profiles[e].displayName=t,this.saveConfig(),!0):!1}updateUrls(e,t){let n=this.config.profiles[e];if(!n)return!1;let i=!1;return t.matrixUrl&&t.matrixUrl!==n.matrixUrl&&(n.matrixUrl=t.matrixUrl,i=!0),t.realmServerUrl&&t.realmServerUrl!==n.realmServerUrl&&(n.realmServerUrl=t.realmServerUrl,i=!0),i&&(n.realmTokens=void 0,n.realmServerToken=void 0,this.saveConfig()),i}setRealmToken(e,t){let n=this.getActiveProfile();n&&(n.profile.realmTokens||(n.profile.realmTokens={}),n.profile.realmTokens[e]=t,this.saveConfig())}getRealmToken(e){return this.getActiveProfile()?.profile.realmTokens?.[e]}setRealmServerToken(e){let t=this.getActiveProfile();t&&(t.profile.realmServerToken=e,this.saveConfig())}getRealmServerToken(){return this.getActiveProfile()?.profile.realmServerToken}async loginToMatrix(){let e=this.getActiveProfile();if(!e)throw new Error("No active profile");let{id:t,profile:n}=e,i=qe(t);return dl(n.matrixUrl,i,n.password)}async getOrRefreshServerToken(){let e=this.getRealmServerToken();if(e&&!Wg(e))return e;let t=await this.loginToMatrix(),i=this.getActiveProfile().profile.realmServerUrl.replace(/\/$/,""),o=await Sn(t,i);return this.setRealmServerToken(o),o}async refreshServerToken(){let e=await this.loginToMatrix(),n=this.getActiveProfile().profile.realmServerUrl.replace(/\/$/,""),i=await Sn(e,n);return this.setRealmServerToken(i),i}findRealmTokenForUrl(e){let n=this.getActiveProfile()?.profile.realmTokens;if(n){for(let[i,o]of Object.entries(n))if(e.startsWith(i)&&o)return o}}async fetchAndStoreAllRealmTokens(){let e=await this.getOrRefreshServerToken(),n=this.getActiveProfile().profile.realmServerUrl.replace(/\/$/,""),i=await vn(n,e);for(let[o,s]of Object.entries(i))this.setRealmToken(o,s)}async getRealmTokenForUrl(e){let t=this.findRealmTokenForUrl(e);if(t)return t;try{await this.fetchAndStoreAllRealmTokens()}catch{return}return this.findRealmTokenForUrl(e)}buildHeaders(e,t,n){let i=e instanceof Request?new Headers(e.headers):new Headers,o=new Headers(t?.headers);for(let[s,a]of o)i.set(s,a);return i.has("Authorization")||i.set("Authorization",n),i}async authedRealmFetch(e,t){let n=e instanceof Request?e.url:e instanceof URL?e.href:e,i=await this.getRealmTokenForUrl(n);if(i){let l=this.buildHeaders(e,t,i),u=await fetch(e,{...t,headers:l});if(u.status!==401)return u}let o=this.getActiveProfile();if(o&&(o.profile.realmTokens={},o.profile.realmServerToken=void 0,this.saveConfig()),await this.fetchAndStoreAllRealmTokens(),i=this.findRealmTokenForUrl(n),!i)throw new Error(`No realm token available for ${n}. The realm may not be accessible.`);let s=this.buildHeaders(e,t,i);return await fetch(e,{...t,headers:s})}async authedRealmServerFetch(e,t){let n=await this.getOrRefreshServerToken(),i=this.buildHeaders(e,t,n),o=await fetch(e,{...t,headers:i});return o.status===401&&(n=await this.refreshServerToken(),i=this.buildHeaders(e,t,n),o=await fetch(e,{...t,headers:i})),o}async fetchAndStoreRealmToken(e,t){let i=this.getActiveProfile().profile.realmServerUrl.replace(/\/$/,""),s=(await vn(i,t))[e];return s&&this.setRealmToken(e,s),s}async addToUserRealms(e){let t=await this.loginToMatrix();await pl(t,e)}async removeFromUserRealms(e){let t=await this.loginToMatrix();return hl(t,e)}async getUserRealms(){let e=await this.loginToMatrix();return Yt(e)}async migrateFromEnv(){let e=process.env.MATRIX_URL,t=process.env.MATRIX_USERNAME,n=process.env.MATRIX_PASSWORD,i=process.env.REALM_SERVER_URL;if(!e||!t||!n||!i)return null;let s=e.includes("boxel.ai")?"boxel.ai":"stack.cards",a=`@${t}:${s}`;return this.config.profiles[a]?(this.config.profiles[a].password!==n&&(this.config.profiles[a].password=n,this.saveConfig()),{profileId:a,created:!1}):(await this.addProfile(a,n,void 0,e,i),{profileId:a,created:!0})}printStatus(){let e=this.getActiveProfile();e?(console.log(`
32
+ ${K}Active Profile:${f} ${fe(e.id)}`),console.log(` ${g}Display Name:${f} ${e.profile.displayName}`),console.log(` ${g}Matrix URL:${f} ${e.profile.matrixUrl}`),console.log(` ${g}Realm Server:${f} ${e.profile.realmServerUrl}`)):process.env.MATRIX_USERNAME?(console.log(`
33
+ ${K}Using environment variables${f} (no profile active)`),console.log(` ${g}Username:${f} ${process.env.MATRIX_USERNAME}`)):(console.log(`
34
+ ${C}No active profile and no environment variables set.${f}`),console.log(`Run ${_}boxel profile add${f} to create a profile.`))}},_n=null;function A(){return _n||(_n=new kn),_n}var Cn=O(require("readline")),wl=require("stream");function Q(r){let e=Cn.createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{e.question(r,n=>{e.close(),t(n.trim())})})}function An(r){let e=new wl.Writable({write:(n,i,o)=>o()}),t=Cn.createInterface({input:process.stdin,output:e,terminal:!0});return new Promise((n,i)=>{let o=process.stdin,s=o.readableFlowing;o.isTTY&&o.setRawMode(!0);let a=()=>{o.removeListener("data",l),o.isTTY&&o.setRawMode(!1),t.close(),s||o.pause()},l=c=>{try{let m=c.toString().split("\x1B[200~").join("").split("\x1B[201~").join("");for(let d of m)if(d===`
35
35
  `||d==="\r"){a(),process.stdout.write(`
36
- `),n(u);return}else d===""?(a(),process.exit()):d==="\x7F"||d==="\b"?u.length>0&&(u=u.slice(0,-1),process.stdout.write("\b \b")):d>=" "&&(u+=d,process.stdout.write("*"))}catch(m){a(),i(m)}},u="";try{process.stdout.write(r),o.on("data",l),o.resume()}catch(c){a(),i(c)}})}async function me(r){let e=process.env.BOXEL_REALM_SECRET_SEED;if(e)return e;if(r){if(!process.stdin.isTTY)throw new Error("Cannot prompt for realm secret seed: stdin is not a TTY. Set BOXEL_REALM_SECRET_SEED in the environment instead.");return Cn("Realm secret seed: ")}}var An={staging:{domain:"stack.cards",matrixUrl:"https://matrix-staging.stack.cards",realmServerUrl:"https://realms-staging.stack.cards/"},production:{domain:"boxel.ai",matrixUrl:"https://matrix.boxel.ai",realmServerUrl:"https://app.boxel.ai/"},local:{domain:"localhost",matrixUrl:"http://localhost:8008",realmServerUrl:"http://localhost:4201/"}};function Kt(r,e){let t=r.trim(),n;try{n=new URL(t)}catch{console.error(`${h}Error:${f} ${e} "${r}" is not a valid URL.`),process.exit(1)}return n.protocol!=="http:"&&n.protocol!=="https:"&&(console.error(`${h}Error:${f} ${e} "${r}" must use http:// or https://.`),process.exit(1)),t}function Bg(r){return r.toLowerCase().replace(/\//g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function El(){let r=process.env.BOXEL_ENVIRONMENT;if(!r||!r.trim())return null;let e=Bg(r);return e||(console.error(`${h}Error:${f} BOXEL_ENVIRONMENT="${r}" contains no slug characters (expected letters, digits, or "-").`),process.exit(1)),{domain:`${e}.localhost`,matrixUrl:`http://matrix.${e}.localhost`,realmServerUrl:`http://realm-server.${e}.localhost/`}}async function bl(r,e,t){let n=A();switch(r){case"list":await $l(n);break;case"add":{let i=t?.password||process.env.BOXEL_PASSWORD;if(t?.user&&i){let o=t.matrixUrl?Kt(t.matrixUrl,"--matrix-url"):void 0,s=t.realmServerUrl?Kt(t.realmServerUrl,"--realm-server-url"):void 0,c=!(zt(t.user)!=="unknown")&&(!o||!s)?El():null;c&&console.log(`${y}Using BOXEL_ENVIRONMENT=${process.env.BOXEL_ENVIRONMENT}${f}`),await Kg(n,t.user,i,t.name,o??c?.matrixUrl,s??c?.realmServerUrl)}else await Xg(n,El());break}case"switch":e||(console.error(`${h}Error:${f} Please specify a profile to switch to.`),console.log("Usage: boxel profile switch <profile-id>"),console.log(`
36
+ `),n(u);return}else d===""?(a(),process.exit()):d==="\x7F"||d==="\b"?u.length>0&&(u=u.slice(0,-1),process.stdout.write("\b \b")):d>=" "&&(u+=d,process.stdout.write("*"))}catch(m){a(),i(m)}},u="";try{process.stdout.write(r),o.on("data",l),o.resume()}catch(c){a(),i(c)}})}async function me(r){let e=process.env.BOXEL_REALM_SECRET_SEED;if(e)return e;if(r){if(!process.stdin.isTTY)throw new Error("Cannot prompt for realm secret seed: stdin is not a TTY. Set BOXEL_REALM_SECRET_SEED in the environment instead.");return An("Realm secret seed: ")}}var Pn={staging:{domain:"stack.cards",matrixUrl:"https://matrix-staging.stack.cards",realmServerUrl:"https://realms-staging.stack.cards/"},production:{domain:"boxel.ai",matrixUrl:"https://matrix.boxel.ai",realmServerUrl:"https://app.boxel.ai/"},local:{domain:"localhost",matrixUrl:"http://localhost:8008",realmServerUrl:"http://localhost:4201/"}};function Jt(r,e){let t=r.trim(),n;try{n=new URL(t)}catch{console.error(`${h}Error:${f} ${e} "${r}" is not a valid URL.`),process.exit(1)}return n.protocol!=="http:"&&n.protocol!=="https:"&&(console.error(`${h}Error:${f} ${e} "${r}" must use http:// or https://.`),process.exit(1)),t}function Bg(r){return r.toLowerCase().replace(/\//g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function El(){let r=process.env.BOXEL_ENVIRONMENT;if(!r||!r.trim())return null;let e=Bg(r);return e||(console.error(`${h}Error:${f} BOXEL_ENVIRONMENT="${r}" contains no slug characters (expected letters, digits, or "-").`),process.exit(1)),{domain:`${e}.localhost`,matrixUrl:`http://matrix.${e}.localhost`,realmServerUrl:`http://realm-server.${e}.localhost/`}}async function bl(r,e,t){let n=A();switch(r){case"list":await $l(n);break;case"add":{let i=t?.password||process.env.BOXEL_PASSWORD;if(t?.user&&i){let o=t.matrixUrl?Jt(t.matrixUrl,"--matrix-url"):void 0,s=t.realmServerUrl?Jt(t.realmServerUrl,"--realm-server-url"):void 0,c=!(Xt(t.user)!=="unknown")&&(!o||!s)?El():null;c&&console.log(`${g}Using BOXEL_ENVIRONMENT=${process.env.BOXEL_ENVIRONMENT}${f}`),await Kg(n,t.user,i,t.name,o??c?.matrixUrl,s??c?.realmServerUrl)}else await Xg(n,El());break}case"switch":e||(console.error(`${h}Error:${f} Please specify a profile to switch to.`),console.log("Usage: boxel profile switch <profile-id>"),console.log(`
37
37
  Available profiles:`),await $l(n),process.exit(1)),await zg(n,e);break;case"remove":e||(console.error(`${h}Error:${f} Please specify a profile to remove.`),process.exit(1)),await Jg(n,e);break;case"migrate":await Qg(n);break;default:n.printStatus(),console.log(`
38
- ${y}Commands:${f}`),console.log(` ${_}boxel profile list${f} List all profiles`),console.log(` ${_}boxel profile add${f} Add a new profile`),console.log(` ${_}boxel profile switch${f} Switch active profile`),console.log(` ${_}boxel profile remove${f} Remove a profile`),console.log(` ${_}boxel profile migrate${f} Import from .env file`)}}async function $l(r){let e=r.listProfiles(),t=r.getActiveProfileId();if(e.length===0){console.log(`
38
+ ${g}Commands:${f}`),console.log(` ${_}boxel profile list${f} List all profiles`),console.log(` ${_}boxel profile add${f} Add a new profile`),console.log(` ${_}boxel profile switch${f} Switch active profile`),console.log(` ${_}boxel profile remove${f} Remove a profile`),console.log(` ${_}boxel profile migrate${f} Import from .env file`)}}async function $l(r){let e=r.listProfiles(),t=r.getActiveProfileId();if(e.length===0){console.log(`
39
39
  ${C}No profiles configured.${f}`),console.log(`Run ${_}boxel profile add${f} to create one.`);return}console.log(`
40
- ${J}Saved Profiles:${f}
41
- `);for(let n of e){let i=r.getProfile(n),o=n===t,s=zt(n),a=o?`${S}\u2605${f} `:" ",l=Jt(n),u=s==="production"?ne:_;console.log(`${a}${J}${n}${f}`),console.log(` ${y}Name:${f} ${i.displayName}`),console.log(` ${y}Environment:${f} ${u}${l}${f}`),console.log(` ${y}Realm Server:${f} ${i.realmServerUrl}`),console.log("")}t&&console.log(`${y}\u2605 = active profile${f}`)}async function Yg(){console.log("Which environment?"),console.log(` ${_}1${f}) Staging (realms-staging.stack.cards)`),console.log(` ${ne}2${f}) Production (app.boxel.ai)`),console.log(` ${S}3${f}) Local (localhost:4201)`),console.log(` ${C}4${f}) Custom (enter your own URLs)`);let r=await K(`
42
- Choice [1/2/3/4]: `);if(r==="4"){let e=await K("Matrix server URL: ");e||(console.error(`${h}Error:${f} Matrix server URL is required.`),process.exit(1));let t=Kt(e,"Matrix server URL"),n=await K("Realm server URL: ");n||(console.error(`${h}Error:${f} Realm server URL is required.`),process.exit(1));let i=Kt(n,"Realm server URL"),o=new URL(t).hostname||"custom";return{domain:await K(`Domain for Matrix ID [${o}]: `)||o,matrixUrl:t,realmServerUrl:i}}return r==="3"?{...An.local}:r==="2"?{...An.production}:{...An.staging}}async function Xg(r,e){console.log(`
43
- ${J}Add New Profile${f}
44
- `);let t,n,i;if(e)console.log(`${y}Using BOXEL_ENVIRONMENT=${process.env.BOXEL_ENVIRONMENT}${f}`),t=e.domain,n=e.matrixUrl,i=e.realmServerUrl;else{let m=await Yg();t=m.domain,n=m.matrixUrl,i=m.realmServerUrl}console.log(`
45
- Enter your Boxel username (without @ or domain)`),console.log(`${y}Example: ctse, aallen90${f}`);let o=await K("Username: ");o||(console.error(`${h}Error:${f} Username is required.`),process.exit(1));let s=`@${o}:${t}`;if(r.getProfile(s)&&(console.log(`
46
- ${C}Profile ${s} already exists.${f}`),(await K("Overwrite? [y/N]: ")).toLowerCase()!=="y")){console.log("Cancelled.");return}let a=await Cn("Password: ");a||(console.error(`${h}Error:${f} Password is required.`),process.exit(1));let l=`${o} \xB7 ${t}`,c=await K(`Display name [${l}]: `)||l;await r.addProfile(s,a,c,n,i),console.log(`
47
- ${S}\u2713${f} Profile created: ${fe(s)}`),r.getActiveProfileId()===s?console.log(`${y}This profile is now active.${f}`):(await K("Switch to this profile now? [Y/n]: ")).toLowerCase()!=="n"&&(r.switchProfile(s),console.log(`${S}\u2713${f} Switched to ${fe(s)}`))}async function zg(r,e){let t=r.listProfiles(),n=e;if(!t.includes(e)){let i=t.filter(o=>{let s=je(o);return o.includes(e)||s===e});if(i.length===0){console.error(`${h}Error:${f} Profile not found: ${e}`),console.log(`
40
+ ${K}Saved Profiles:${f}
41
+ `);for(let n of e){let i=r.getProfile(n),o=n===t,s=Xt(n),a=o?`${S}\u2605${f} `:" ",l=zt(n),u=s==="production"?ie:_;console.log(`${a}${K}${n}${f}`),console.log(` ${g}Name:${f} ${i.displayName}`),console.log(` ${g}Environment:${f} ${u}${l}${f}`),console.log(` ${g}Realm Server:${f} ${i.realmServerUrl}`),console.log("")}t&&console.log(`${g}\u2605 = active profile${f}`)}async function Yg(){console.log("Which environment?"),console.log(` ${_}1${f}) Staging (realms-staging.stack.cards)`),console.log(` ${ie}2${f}) Production (app.boxel.ai)`),console.log(` ${S}3${f}) Local (localhost:4201)`),console.log(` ${C}4${f}) Custom (enter your own URLs)`);let r=await Q(`
42
+ Choice [1/2/3/4]: `);if(r==="4"){let e=await Q("Matrix server URL: ");e||(console.error(`${h}Error:${f} Matrix server URL is required.`),process.exit(1));let t=Jt(e,"Matrix server URL"),n=await Q("Realm server URL: ");n||(console.error(`${h}Error:${f} Realm server URL is required.`),process.exit(1));let i=Jt(n,"Realm server URL"),o=new URL(t).hostname||"custom";return{domain:await Q(`Domain for Matrix ID [${o}]: `)||o,matrixUrl:t,realmServerUrl:i}}return r==="3"?{...Pn.local}:r==="2"?{...Pn.production}:{...Pn.staging}}async function Xg(r,e){console.log(`
43
+ ${K}Add New Profile${f}
44
+ `);let t,n,i;if(e)console.log(`${g}Using BOXEL_ENVIRONMENT=${process.env.BOXEL_ENVIRONMENT}${f}`),t=e.domain,n=e.matrixUrl,i=e.realmServerUrl;else{let m=await Yg();t=m.domain,n=m.matrixUrl,i=m.realmServerUrl}console.log(`
45
+ Enter your Boxel username (without @ or domain)`),console.log(`${g}Example: ctse, aallen90${f}`);let o=await Q("Username: ");o||(console.error(`${h}Error:${f} Username is required.`),process.exit(1));let s=`@${o}:${t}`;if(r.getProfile(s)&&(console.log(`
46
+ ${C}Profile ${s} already exists.${f}`),(await Q("Overwrite? [y/N]: ")).toLowerCase()!=="y")){console.log("Cancelled.");return}let a=await An("Password: ");a||(console.error(`${h}Error:${f} Password is required.`),process.exit(1));let l=`${o} \xB7 ${t}`,c=await Q(`Display name [${l}]: `)||l;await r.addProfile(s,a,c,n,i),console.log(`
47
+ ${S}\u2713${f} Profile created: ${fe(s)}`),r.getActiveProfileId()===s?console.log(`${g}This profile is now active.${f}`):(await Q("Switch to this profile now? [Y/n]: ")).toLowerCase()!=="n"&&(r.switchProfile(s),console.log(`${S}\u2713${f} Switched to ${fe(s)}`))}async function zg(r,e){let t=r.listProfiles(),n=e;if(!t.includes(e)){let i=t.filter(o=>{let s=qe(o);return o.includes(e)||s===e});if(i.length===0){console.error(`${h}Error:${f} Profile not found: ${e}`),console.log(`
48
48
  Available profiles:`);for(let o of t)console.log(` ${o}`);process.exit(1)}else if(i.length===1)n=i[0];else{console.error(`${h}Error:${f} Ambiguous profile: ${e}`),console.log(`
49
- Matching profiles:`);for(let o of i)console.log(` ${o}`);process.exit(1)}}r.switchProfile(n)?console.log(`${S}\u2713${f} Switched to ${fe(n)}`):(console.error(`${h}Error:${f} Failed to switch profile.`),process.exit(1))}async function Jg(r,e){if(r.getProfile(e)||(console.error(`${h}Error:${f} Profile not found: ${e}`),process.exit(1)),(await K(`Remove profile ${e}? [y/N]: `)).toLowerCase()!=="y"){console.log("Cancelled.");return}if(await r.removeProfile(e)){console.log(`${S}\u2713${f} Profile removed.`);let i=r.getActiveProfileId();i&&console.log(`Active profile is now: ${fe(i)}`)}else console.error(`${h}Error:${f} Failed to remove profile.`),process.exit(1)}async function Kg(r,e,t,n,i,o){if((!e.startsWith("@")||!e.includes(":"))&&(console.error(`${h}Error:${f} Invalid Matrix ID format. Expected @user:domain`),process.exit(1)),r.getProfile(e)){console.log(`${C}Profile ${e} already exists. Updating password.${f}`),await r.updatePassword(e,t),n&&r.updateDisplayName(e,n),(i||o)&&r.updateUrls(e,{matrixUrl:i,realmServerUrl:o})&&console.log(`${y}Updated server URLs and cleared cached realm tokens.${f}`),console.log(`${S}\u2713${f} Profile updated: ${fe(e)}`);return}try{await r.addProfile(e,t,n,i,o)}catch(a){console.error(`${h}Error:${f} ${a instanceof Error?a.message:String(a)}`),process.exit(1)}console.log(`${S}\u2713${f} Profile created: ${fe(e)}`),r.getActiveProfileId()!==e&&console.log(`${y}Use 'boxel profile switch ${e}' to switch to this profile.${f}`)}async function Qg(r){console.log(`
50
- ${J}Migrate from .env${f}
49
+ Matching profiles:`);for(let o of i)console.log(` ${o}`);process.exit(1)}}r.switchProfile(n)?console.log(`${S}\u2713${f} Switched to ${fe(n)}`):(console.error(`${h}Error:${f} Failed to switch profile.`),process.exit(1))}async function Jg(r,e){if(r.getProfile(e)||(console.error(`${h}Error:${f} Profile not found: ${e}`),process.exit(1)),(await Q(`Remove profile ${e}? [y/N]: `)).toLowerCase()!=="y"){console.log("Cancelled.");return}if(await r.removeProfile(e)){console.log(`${S}\u2713${f} Profile removed.`);let i=r.getActiveProfileId();i&&console.log(`Active profile is now: ${fe(i)}`)}else console.error(`${h}Error:${f} Failed to remove profile.`),process.exit(1)}async function Kg(r,e,t,n,i,o){if((!e.startsWith("@")||!e.includes(":"))&&(console.error(`${h}Error:${f} Invalid Matrix ID format. Expected @user:domain`),process.exit(1)),r.getProfile(e)){console.log(`${C}Profile ${e} already exists. Updating password.${f}`),await r.updatePassword(e,t),n&&r.updateDisplayName(e,n),(i||o)&&r.updateUrls(e,{matrixUrl:i,realmServerUrl:o})&&console.log(`${g}Updated server URLs and cleared cached realm tokens.${f}`),console.log(`${S}\u2713${f} Profile updated: ${fe(e)}`);return}try{await r.addProfile(e,t,n,i,o)}catch(a){console.error(`${h}Error:${f} ${a instanceof Error?a.message:String(a)}`),process.exit(1)}console.log(`${S}\u2713${f} Profile created: ${fe(e)}`),r.getActiveProfileId()!==e&&console.log(`${g}Use 'boxel profile switch ${e}' to switch to this profile.${f}`)}async function Qg(r){console.log(`
50
+ ${K}Migrate from .env${f}
51
51
  `);let e=process.env.MATRIX_URL,t=process.env.MATRIX_USERNAME,n=process.env.MATRIX_PASSWORD,i=process.env.REALM_SERVER_URL;if(!e||!t||!n||!i){console.log(`${C}No complete credentials found in environment variables.${f}`),console.log(`
52
52
  Required variables: MATRIX_URL, MATRIX_USERNAME, MATRIX_PASSWORD, REALM_SERVER_URL`);return}let o=await r.migrateFromEnv();o?o.created?(console.log(`${S}\u2713${f} Created profile: ${fe(o.profileId)}`),console.log(`
53
- ${y}You can now remove credentials from .env if desired.${f}`)):(console.log(`${C}Profile ${fe(o.profileId)} already exists.${f} Password has been updated if it changed.`),console.log(`
54
- ${y}Use 'boxel profile add -u ${o.profileId} -p <password>' to update other fields.${f}`)):console.log(`${C}Migration failed.${f}`)}var le=O(require("fs")),Oe=O(require("path"));var qe=O(require("fs")),q=O(require("path"));var rt=!1,Zg=console.log.bind(console),ey=console.info.bind(console),ty=console.debug.bind(console);function Zt(r){if(r!==rt)if(rt=r,rt){let e=()=>{};console.log=e,console.info=e,console.debug=e}else console.log=Zg,console.info=ey,console.debug=ty}function Rl(){return rt}var N={info(...r){rt||process.stderr.write(r.map(Qt).join(" ")+`
55
- `)},warn(...r){process.stderr.write(r.map(Qt).join(" ")+`
56
- `)},error(...r){process.stderr.write(r.map(Qt).join(" ")+`
57
- `)},output(...r){process.stdout.write(r.map(Qt).join(" ")+`
58
- `)}};function Qt(r){if(typeof r=="string")return r;if(r instanceof Error)return r.stack??r.message;try{return JSON.stringify(r)}catch{return String(r)}}var Sl=!1,ry=new Set([".git","node_modules","dist",".boxel-history",".claude"]);function ny(r){return ry.has(r)}function iy(r){return r==="stack.cards"||r.endsWith(".stack.cards")?"stack.cards":r==="boxel.ai"||r.endsWith(".boxel.ai")?"boxel.ai":r}function Pn(r){if(!r)return!1;let e;try{e=decodeURIComponent(r)}catch{return!1}return!(e==="."||e===".."||e.includes("/")||e.includes("\\")||e.includes("\0"))}function oy(r){let e;try{e=new URL(r)}catch{return null}let t=iy(e.hostname);if(!Pn(t))return null;let n=e.pathname.replace(/^\/|\/$/g,"").split("/").filter(Boolean),i=n[0]??"unknown-owner",o=n[1]??n[0]??"workspace";return!Pn(i)||!Pn(o)?null:q.join(t,i,o)}function sy(r,e){let t=oy(r);return t===null?null:q.resolve(e,t)}function ay(r){let e;try{e=qe.readFileSync(r,"utf-8")}catch{return null}let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null)return null;let n=t.realmUrl;return typeof n!="string"||n===""?null:{realmUrl:n}}function vl(r,e){let t=q.join(r,".boxel-sync.json");qe.existsSync(t)&&e.push(t)}function er(r){try{return qe.readdirSync(r,{withFileTypes:!0}).filter(e=>e.isDirectory()&&!ny(e.name)).map(e=>q.join(r,e.name))}catch{return[]}}function ly(r){let e=[],t=q.resolve(r);for(let n of er(t))vl(n,e);for(let n of er(t))for(let i of er(n))for(let o of er(i))vl(o,e);return e}function cy(r,e){let t=q.relative(r,e);return t===""?!0:t.startsWith("..")?!1:!q.isAbsolute(t)}function Tn(r){let e=q.resolve(r),t=ly(e),n=new Set,i=[];for(let o of t){if(n.has(o))continue;n.add(o);let s=ay(o);if(!s)continue;let a=sy(s.realmUrl,e);if(a===null||!cy(e,a))continue;let l=q.dirname(o);q.resolve(l)!==q.resolve(a)&&i.push({manifestPath:o,currentDir:l,expectedDir:a,realmUrl:s.realmUrl})}return i}function xl(r){if(Sl||process.env.BOXEL_DISABLE_PATH_WARNING==="1"||Rl())return;let e=Tn(r);if(e.length===0)return;Sl=!0,console.warn(`
53
+ ${g}You can now remove credentials from .env if desired.${f}`)):(console.log(`${C}Profile ${fe(o.profileId)} already exists.${f} Password has been updated if it changed.`),console.log(`
54
+ ${g}Use 'boxel profile add -u ${o.profileId} -p <password>' to update other fields.${f}`)):console.log(`${C}Migration failed.${f}`)}var le=O(require("fs")),Ce=O(require("path"));var Ge=O(require("fs")),q=O(require("path"));var nt=!1,Zg=console.log.bind(console),ey=console.info.bind(console),ty=console.debug.bind(console);function Qt(r){if(r!==nt)if(nt=r,nt){let e=()=>{};console.log=e,console.info=e,console.debug=e}else console.log=Zg,console.info=ey,console.debug=ty}function Rl(){return nt}var N={info(...r){nt||process.stderr.write(r.map(Kt).join(" ")+`
55
+ `)},warn(...r){process.stderr.write(r.map(Kt).join(" ")+`
56
+ `)},error(...r){process.stderr.write(r.map(Kt).join(" ")+`
57
+ `)},output(...r){process.stdout.write(r.map(Kt).join(" ")+`
58
+ `)}};function Kt(r){if(typeof r=="string")return r;if(r instanceof Error)return r.stack??r.message;try{return JSON.stringify(r)}catch{return String(r)}}var Sl=!1,ry=new Set([".git","node_modules","dist",".boxel-history",".claude"]);function ny(r){return ry.has(r)}function iy(r){return r==="stack.cards"||r.endsWith(".stack.cards")?"stack.cards":r==="boxel.ai"||r.endsWith(".boxel.ai")?"boxel.ai":r}function Tn(r){if(!r)return!1;let e;try{e=decodeURIComponent(r)}catch{return!1}return!(e==="."||e===".."||e.includes("/")||e.includes("\\")||e.includes("\0"))}function oy(r){let e;try{e=new URL(r)}catch{return null}let t=iy(e.hostname);if(!Tn(t))return null;let n=e.pathname.replace(/^\/|\/$/g,"").split("/").filter(Boolean),i=n[0]??"unknown-owner",o=n[1]??n[0]??"workspace";return!Tn(i)||!Tn(o)?null:q.join(t,i,o)}function sy(r,e){let t=oy(r);return t===null?null:q.resolve(e,t)}function ay(r){let e;try{e=Ge.readFileSync(r,"utf-8")}catch{return null}let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null)return null;let n=t.realmUrl;return typeof n!="string"||n===""?null:{realmUrl:n}}function vl(r,e){let t=q.join(r,".boxel-sync.json");Ge.existsSync(t)&&e.push(t)}function Zt(r){try{return Ge.readdirSync(r,{withFileTypes:!0}).filter(e=>e.isDirectory()&&!ny(e.name)).map(e=>q.join(r,e.name))}catch{return[]}}function ly(r){let e=[],t=q.resolve(r);for(let n of Zt(t))vl(n,e);for(let n of Zt(t))for(let i of Zt(n))for(let o of Zt(i))vl(o,e);return e}function cy(r,e){let t=q.relative(r,e);return t===""?!0:t.startsWith("..")?!1:!q.isAbsolute(t)}function Ln(r){let e=q.resolve(r),t=ly(e),n=new Set,i=[];for(let o of t){if(n.has(o))continue;n.add(o);let s=ay(o);if(!s)continue;let a=sy(s.realmUrl,e);if(a===null||!cy(e,a))continue;let l=q.dirname(o);q.resolve(l)!==q.resolve(a)&&i.push({manifestPath:o,currentDir:l,expectedDir:a,realmUrl:s.realmUrl})}return i}function xl(r){if(Sl||process.env.BOXEL_DISABLE_PATH_WARNING==="1"||Rl())return;let e=Ln(r);if(e.length===0)return;Sl=!0,console.warn(`
59
59
  \u26A0\uFE0F Detected local realm directories at legacy local paths:`);let t=q.resolve(r);for(let n of e.slice(0,5)){let i=q.relative(t,n.currentDir)||".",o=q.relative(t,n.expectedDir)||".";console.warn(` - ${i} -> ${o}`)}e.length>5&&console.warn(` ...and ${e.length-5} more`),console.warn(`
60
60
  Run to preview:`),console.warn(" boxel consolidate-workspaces . --dry-run"),console.warn("Then apply:"),console.warn(` boxel consolidate-workspaces .
61
- `)}function uy(r){le.existsSync(r)||le.mkdirSync(r,{recursive:!0})}function fy(r,e){try{le.renameSync(r,e)}catch(t){let n=t;if(n.code!=="EXDEV")throw n;le.cpSync(r,e,{recursive:!0}),le.rmSync(r,{recursive:!0,force:!0})}}async function my(r,e){let t=Oe.resolve(r||"."),n=Tn(t);if(n.length===0){console.log(`No misplaced local realm paths found under ${t}`);return}console.log(`Found ${n.length} misplaced local realm path(s):
62
- `);let i=0,o=0;for(let s of n){let a=Oe.relative(t,s.currentDir)||".",l=Oe.relative(t,s.expectedDir)||".";if(console.log(`- ${a} -> ${l}`),!e.dryRun){if(le.existsSync(s.expectedDir)){console.warn(" Skipping: target path already exists"),o+=1;continue}uy(Oe.dirname(s.expectedDir));try{fy(s.currentDir,s.expectedDir),i+=1}catch(u){let c=u instanceof Error?u.message:String(u);console.warn(` Skipping: failed to move (${c})`),o+=1}}}if(e.dryRun){console.log(`
61
+ `)}function uy(r){le.existsSync(r)||le.mkdirSync(r,{recursive:!0})}function fy(r,e){try{le.renameSync(r,e)}catch(t){let n=t;if(n.code!=="EXDEV")throw n;le.cpSync(r,e,{recursive:!0}),le.rmSync(r,{recursive:!0,force:!0})}}async function my(r,e){let t=Ce.resolve(r||"."),n=Ln(t);if(n.length===0){console.log(`No misplaced local realm paths found under ${t}`);return}console.log(`Found ${n.length} misplaced local realm path(s):
62
+ `);let i=0,o=0;for(let s of n){let a=Ce.relative(t,s.currentDir)||".",l=Ce.relative(t,s.expectedDir)||".";if(console.log(`- ${a} -> ${l}`),!e.dryRun){if(le.existsSync(s.expectedDir)){console.warn(" Skipping: target path already exists"),o+=1;continue}uy(Ce.dirname(s.expectedDir));try{fy(s.currentDir,s.expectedDir),i+=1}catch(u){let c=u instanceof Error?u.message:String(u);console.warn(` Skipping: failed to move (${c})`),o+=1}}}if(e.dryRun){console.log(`
63
63
  [DRY RUN] No directories moved.`);return}console.log(`
64
- Moved ${i} director${i===1?"y":"ies"}.`),o>0&&console.log(`Skipped ${o} due to existing target paths or move failures.`)}function _l(r){r.command("consolidate-workspaces").description("Move local realm mirror directories into the canonical <root>/<domain>/<owner>/<realm> layout").argument("[root-dir]","Root directory to scan (default: current directory)").option("--dry-run","Preview without moving anything").action(async(e,t)=>{await my(e,t)})}async function dy(r,e,t){let n=t?.profileManager??A();if(!n.getActiveProfile())throw new Error("No active profile. Run `boxel profile add` to create one.");let o=new URL(e,P(r)).href,s;try{s=await n.authedRealmFetch(o,{method:"GET",headers:{Accept:"*/*"}})}catch(l){return{ok:!1,error:l instanceof Error?l.message:String(l)}}if(!s.ok){let l=await s.text().catch(()=>"(no body)");return{ok:!1,status:s.status,error:`HTTP ${s.status}: ${l.slice(0,300)}`}}let a=await s.text();return{ok:!0,status:s.status,content:a}}function kl(r){r.command("read-transpiled").description("Debugging tool ONLY for investigating runtime errors in .gts modules you've written. Use when an eval or instantiate error reports a line/column number \u2014 those line numbers refer to the transpiled output, not your .gts source, so fetching the transpiled output is how you locate the offending source construct. Never use the transpiled output as a reference for how to write code: do not copy its patterns (setComponentTemplate, precompileTemplate, wire-format templates, base64 CSS imports) into source. Always write idiomatic Ember / <template>-tag / CardDef source.").argument("<path>","Realm-relative module path. The .gts extension is optional \u2014 the realm accepts either form.").requiredOption("--realm <realm-url>","The realm URL to fetch from").option("--json","Output raw JSON response").action(async(e,t)=>{let n;try{n=await dy(t.realm,e)}catch(i){console.error(`${h}Error:${f} ${i instanceof Error?i.message:String(i)}`),process.exit(1)}t.json?N.output(JSON.stringify(n,null,2)):n.ok?N.output(n.content??""):(console.error(`${y}Status:${f} ${n.status??"(no status)"}`),console.error(`${h}Error:${f} ${n.error}`)),n.ok||process.exit(1)})}async function py(r,e){let t=e?.profileManager??A();if(!t.getActiveProfile())return{ok:!1,error:M};let i=e?.cancelPending??!1,o=`${P(r)}_cancel-indexing-job`;try{let s=await t.authedRealmFetch(o,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({cancelPending:i})});if(!s.ok){let a=await s.text().catch(()=>"(no body)");return{ok:!1,error:`HTTP ${s.status}: ${a.slice(0,300)}`}}return{ok:!0}}catch(s){return{ok:!1,error:s instanceof Error?s.message:String(s)}}}function Ol(r){r.command("cancel-indexing").description("Cancel running indexing jobs for a realm (use --cancel-pending to also cancel queued jobs)").requiredOption("--realm <realm-url>","URL of the realm to cancel indexing for").option("--cancel-pending","Also cancel queued/pending indexing jobs (default: cancel running only)").option("--json","Output raw JSON response").action(async e=>{let t=await py(e.realm,{cancelPending:e.cancelPending});if(e.json)N.output(JSON.stringify(t,null,2)),t.ok||process.exit(1);else if(t.ok){let n=e.cancelPending?"running and pending":"running";console.log(`${S}Cancelled ${n} indexing jobs for ${e.realm}${f}`)}else console.error(`${h}Error:${f} ${t.error}`),process.exit(1)})}var hy=Object.freeze({a:"https://boxel-images.boxel.ai/icons/Letter-a.png",b:"https://boxel-images.boxel.ai/icons/Letter-b.png",c:"https://boxel-images.boxel.ai/icons/Letter-c.png",d:"https://boxel-images.boxel.ai/icons/Letter-d.png",e:"https://boxel-images.boxel.ai/icons/Letter-e.png",f:"https://boxel-images.boxel.ai/icons/Letter-f.png",g:"https://boxel-images.boxel.ai/icons/Letter-g.png",h:"https://boxel-images.boxel.ai/icons/Letter-h.png",i:"https://boxel-images.boxel.ai/icons/Letter-i.png",j:"https://boxel-images.boxel.ai/icons/Letter-j.png",k:"https://boxel-images.boxel.ai/icons/Letter-k.png",l:"https://boxel-images.boxel.ai/icons/Letter-l.png",m:"https://boxel-images.boxel.ai/icons/Letter-m.png",n:"https://boxel-images.boxel.ai/icons/Letter-n.png",o:"https://boxel-images.boxel.ai/icons/Letter-o.png",p:"https://boxel-images.boxel.ai/icons/Letter-p.png",q:"https://boxel-images.boxel.ai/icons/Letter-q.png",r:"https://boxel-images.boxel.ai/icons/Letter-r.png",s:"https://boxel-images.boxel.ai/icons/Letter-s.png",t:"https://boxel-images.boxel.ai/icons/Letter-t.png",u:"https://boxel-images.boxel.ai/icons/Letter-u.png",v:"https://boxel-images.boxel.ai/icons/Letter-v.png",w:"https://boxel-images.boxel.ai/icons/Letter-w.png",x:"https://boxel-images.boxel.ai/icons/Letter-x.png",y:"https://boxel-images.boxel.ai/icons/Letter-y.png",z:"https://boxel-images.boxel.ai/icons/letter-z.png"}),Cl=Object.freeze(["https://boxel-images.boxel.ai/background-images/4k-arabic-teal.jpg","https://boxel-images.boxel.ai/background-images/4k-arrow-weave.jpg","https://boxel-images.boxel.ai/background-images/4k-atmosphere-curvature.jpg","https://boxel-images.boxel.ai/background-images/4k-brushed-slabs.jpg","https://boxel-images.boxel.ai/background-images/4k-coral-reefs.jpg","https://boxel-images.boxel.ai/background-images/4k-crescent-lake.jpg","https://boxel-images.boxel.ai/background-images/4k-curvilinear-stairs.jpg","https://boxel-images.boxel.ai/background-images/4k-desert-dunes.jpg","https://boxel-images.boxel.ai/background-images/4k-doodle-board.jpg","https://boxel-images.boxel.ai/background-images/4k-fallen-leaves.jpg","https://boxel-images.boxel.ai/background-images/4k-flowing-mesh.jpg","https://boxel-images.boxel.ai/background-images/4k-glass-reflection.jpg","https://boxel-images.boxel.ai/background-images/4k-glow-cells.jpg","https://boxel-images.boxel.ai/background-images/4k-granite-peaks.jpg","https://boxel-images.boxel.ai/background-images/4k-green-wormhole.jpg","https://boxel-images.boxel.ai/background-images/4k-joshua-dawn.jpg","https://boxel-images.boxel.ai/background-images/4k-lava-river.jpg","https://boxel-images.boxel.ai/background-images/4k-leaves-moss.jpg","https://boxel-images.boxel.ai/background-images/4k-light-streaks.jpg","https://boxel-images.boxel.ai/background-images/4k-lowres-glitch.jpg","https://boxel-images.boxel.ai/background-images/4k-marble-shimmer.jpg","https://boxel-images.boxel.ai/background-images/4k-metallic-leather.jpg","https://boxel-images.boxel.ai/background-images/4k-microscopic-crystals.jpg","https://boxel-images.boxel.ai/background-images/4k-moon-face.jpg","https://boxel-images.boxel.ai/background-images/4k-mountain-runway.jpg","https://boxel-images.boxel.ai/background-images/4k-origami-flock.jpg","https://boxel-images.boxel.ai/background-images/4k-paint-swirl.jpg","https://boxel-images.boxel.ai/background-images/4k-pastel-triangles.jpg","https://boxel-images.boxel.ai/background-images/4k-perforated-sheet.jpg","https://boxel-images.boxel.ai/background-images/4k-plastic-ripples.jpg","https://boxel-images.boxel.ai/background-images/4k-powder-puff.jpg","https://boxel-images.boxel.ai/background-images/4k-radiant-crystal.jpg","https://boxel-images.boxel.ai/background-images/4k-redrock-canyon.jpg","https://boxel-images.boxel.ai/background-images/4k-rock-portal.jpg","https://boxel-images.boxel.ai/background-images/4k-rolling-hills.jpg","https://boxel-images.boxel.ai/background-images/4k-sand-stone.jpg","https://boxel-images.boxel.ai/background-images/4k-silver-fur.jpg","https://boxel-images.boxel.ai/background-images/4k-spa-pool.jpg","https://boxel-images.boxel.ai/background-images/4k-stained-glass.jpg","https://boxel-images.boxel.ai/background-images/4k-stone-veins.jpg","https://boxel-images.boxel.ai/background-images/4k-tangerine-plains.jpg","https://boxel-images.boxel.ai/background-images/4k-techno-floor.jpg","https://boxel-images.boxel.ai/background-images/4k-thick-frost.jpg","https://boxel-images.boxel.ai/background-images/4k-water-surface.jpg","https://boxel-images.boxel.ai/background-images/4k-watercolor-splashes.jpg","https://boxel-images.boxel.ai/background-images/4k-wildflower-field.jpg","https://boxel-images.boxel.ai/background-images/4k-wood-grain.jpg"]);function Ln(r){if(!r)return;let e=r.toLowerCase().replace(/[^a-z0-9]/g,"").replace(/^[0-9]+/,"");return hy[e.charAt(0)]}function Al(){let r=Math.floor(Math.random()*Cl.length);return Cl[r]}var gy=/^[a-z0-9-]+$/;function Tl(r){r.command("create").description("Create a new realm on the realm server").argument("<realm-name>","realm name (lowercase, numbers, hyphens only)").argument("<display-name>","display name for the realm").option("--background <url>","background image URL").option("--icon <url>","icon image URL").action(async(e,t,n)=>{await Ey(e,t,n)})}async function yy(r,e,t={}){let n=t.profileManager??A(),i=n.getActiveProfile();if(!i)throw new Error("No active profile. Run `boxel profile add` to create one.");let o=i.profile.realmServerUrl.replace(/\/$/,""),s={endpoint:r,name:e,backgroundURL:t.background??Al(),iconURL:t.icon??Ln(e)??Ln(r)},a=await n.authedRealmServerFetch(`${o}/_create-realm`,{method:"POST",headers:{"Content-Type":"application/vnd.api+json"},body:JSON.stringify({data:{type:"realm",attributes:s}})});if(!a.ok){let d;try{d=await a.text()}catch{d="server returned a non-serialized object body"}if(d.includes("[object Object]")&&(d="server returned a non-serialized object body"),d.includes("already exists")){let p=$y(d,o,r),w=await Pl(n,p);try{await n.addToUserRealms(p)}catch{}return{realmUrl:p,created:!1,realmToken:w}}throw new Error(`Realm server returned ${a.status}: ${d}`)}let u=(await a.json())?.data?.id;if(typeof u!="string"||u.trim()==="")throw new Error(`Realm server response did not include a realm URL (data.id) for "${r}".`);let c=P(u),m=await Pl(n,c);try{await n.addToUserRealms(c)}catch{}return t.waitForReady&&m&&await wy(c,m),{realmUrl:c,created:!0,realmToken:m}}async function Pl(r,e){try{let t=await r.getOrRefreshServerToken();return await r.fetchAndStoreRealmToken(e,t)}catch{return}}async function wy(r,e){let t=new URL("_readiness-check",r).href,n=15e3,i=250,o=Date.now(),s;for(;Date.now()-o<n;){try{let a=await fetch(t,{headers:{Accept:"application/vnd.api+json",Authorization:e}});if(a.ok)return;s=`HTTP ${a.status}`}catch(a){s=a instanceof Error?a.message:String(a)}await new Promise(a=>setTimeout(a,i))}throw new Error(`Timed out waiting for realm ${r} to become ready${s?`: ${s}`:""}`)}async function Ey(r,e,t){gy.test(r)||(console.error("Error: realm name must contain only lowercase letters, numbers, and hyphens"),process.exit(1));try{let n=await yy(r,e,t),i=n.created?"created":"already exists";console.log(`${S}Realm ${i}:${f} ${_}${n.realmUrl}${f}`)}catch(n){console.error(`Error: ${n instanceof Error?n.message:String(n)}`),process.exit(1)}}function $y(r,e,t){let n=r.match(/'(https?:\/\/[^']+)'/);if(n)return P(n[1]);throw new Error(`Could not determine realm URL from server error response for endpoint "${t}" on "${e}". The response did not include an explicit realm URL.`)}var ot=O(require("fs"));var Bl=require("child_process"),Y=O(require("fs/promises")),H=O(require("path"));var V=O(require("fs/promises")),G=O(require("path")),Vn=O(ql());var jn=class{value;next;constructor(e){this.value=e}},nt=class{#e;#t;#r;constructor(){this.clear()}enqueue(e){let t=new jn(e);this.#e?(this.#t.next=t,this.#t=t):(this.#e=t,this.#t=t),this.#r++}dequeue(){let e=this.#e;if(e)return this.#e=this.#e.next,this.#r--,this.#e||(this.#t=void 0),e.value}peek(){if(this.#e)return this.#e.value}clear(){this.#e=void 0,this.#t=void 0,this.#r=0}get size(){return this.#r}*[Symbol.iterator](){let e=this.#e;for(;e;)yield e.value,e=e.next}*drain(){for(;this.#e;)yield this.dequeue()}};function qn(r){let e=!1;if(typeof r=="object"&&({concurrency:r,rejectOnClear:e=!1}=r),Gl(r),typeof e!="boolean")throw new TypeError("Expected `rejectOnClear` to be a boolean");let t=new nt,n=0,i=()=>{n<r&&t.size>0&&(n++,t.dequeue().run())},o=()=>{n--,i()},s=async(u,c,m)=>{let d=(async()=>u(...m))();c(d);try{await d}catch{}o()},a=(u,c,m,d)=>{let p={reject:m};new Promise(w=>{p.run=w,t.enqueue(p)}).then(s.bind(void 0,u,c,d)),n<r&&i()},l=(u,...c)=>new Promise((m,d)=>{a(u,m,d,c)});return Object.defineProperties(l,{activeCount:{get:()=>n},pendingCount:{get:()=>t.size},clearQueue:{value(){if(!e){t.clear();return}let u=AbortSignal.abort().reason;for(;t.size>0;)t.dequeue().reject(u)}},concurrency:{get:()=>r,set(u){Gl(u),r=u,queueMicrotask(()=>{for(;n<r&&t.size>0;)i()})}},map:{async value(u,c){let m=Array.from(u,(d,p)=>this(c,d,p));return Promise.all(m)}}}),l}function Gl(r){if(!((Number.isInteger(r)||r===Number.POSITIVE_INFINITY)&&r>0))throw new TypeError("Expected `concurrency` to be a number from 1 and up")}var Fy=Vn.default.default||Vn.default,Uy=new Set([".realm.json"]),Gn=1e4,jy=3e3;function D(r){let e=r.replace(/\\/g,"/").replace(/^\/+/,"");return Uy.has(e)}async function Vl(r){try{return await V.access(r),!0}catch{return!1}}function Hl(r){try{return decodeURIComponent(r)}catch{return r}}var it={CardSource:"application/vnd.card+source",DirectoryListing:"application/vnd.api+json",Mtimes:"application/vnd.api+json"},qy=10,Wl=new Set(["node_modules"]),ie=class{constructor(e,t){this.options=e;this.authenticator=t;this.normalizedRealmUrl=this.normalizeRealmUrl(e.realmUrl)}normalizedRealmUrl;ignoreCache=new Map;remoteLimit=qn(qy);normalizeRealmUrl(e){try{let t=new URL(e),n=t.pathname;return(n.split("/").filter(Boolean).pop()||"").includes(".")?console.warn(`Warning: "${e}" looks like a file URL, not a realm URL.
64
+ Moved ${i} director${i===1?"y":"ies"}.`),o>0&&console.log(`Skipped ${o} due to existing target paths or move failures.`)}function _l(r){r.command("consolidate-workspaces").description("Move local realm mirror directories into the canonical <root>/<domain>/<owner>/<realm> layout").argument("[root-dir]","Root directory to scan (default: current directory)").option("--dry-run","Preview without moving anything").action(async(e,t)=>{await my(e,t)})}async function dy(r,e,t){let n=t?.profileManager??A();if(!n.getActiveProfile())throw new Error("No active profile. Run `boxel profile add` to create one.");let o=new URL(e,P(r)).href,s;try{s=await n.authedRealmFetch(o,{method:"GET",headers:{Accept:"*/*"}})}catch(l){return{ok:!1,error:l instanceof Error?l.message:String(l)}}if(!s.ok){let l=await s.text().catch(()=>"(no body)");return{ok:!1,status:s.status,error:`HTTP ${s.status}: ${l.slice(0,300)}`}}let a=await s.text();return{ok:!0,status:s.status,content:a}}function kl(r){r.command("read-transpiled").description("Debugging tool ONLY for investigating runtime errors in .gts modules you've written. Use when an eval or instantiate error reports a line/column number \u2014 those line numbers refer to the transpiled output, not your .gts source, so fetching the transpiled output is how you locate the offending source construct. Never use the transpiled output as a reference for how to write code: do not copy its patterns (setComponentTemplate, precompileTemplate, wire-format templates, base64 CSS imports) into source. Always write idiomatic Ember / <template>-tag / CardDef source.").argument("<path>","Realm-relative module path. The .gts extension is optional \u2014 the realm accepts either form.").requiredOption("--realm <realm-url>","The realm URL to fetch from").option("--json","Output raw JSON response").action(async(e,t)=>{let n;try{n=await dy(t.realm,e)}catch(i){console.error(`${h}Error:${f} ${i instanceof Error?i.message:String(i)}`),process.exit(1)}t.json?N.output(JSON.stringify(n,null,2)):n.ok?N.output(n.content??""):(console.error(`${g}Status:${f} ${n.status??"(no status)"}`),console.error(`${h}Error:${f} ${n.error}`)),n.ok||process.exit(1)})}async function py(r,e){let t=e?.profileManager??A();if(!t.getActiveProfile())return{ok:!1,error:M};let i=e?.cancelPending??!1,o=`${P(r)}_cancel-indexing-job`;try{let s=await t.authedRealmFetch(o,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({cancelPending:i})});if(!s.ok){let a=await s.text().catch(()=>"(no body)");return{ok:!1,error:`HTTP ${s.status}: ${a.slice(0,300)}`}}return{ok:!0}}catch(s){return{ok:!1,error:s instanceof Error?s.message:String(s)}}}function Ol(r){r.command("cancel-indexing").description("Cancel running indexing jobs for a realm (use --cancel-pending to also cancel queued jobs)").requiredOption("--realm <realm-url>","URL of the realm to cancel indexing for").option("--cancel-pending","Also cancel queued/pending indexing jobs (default: cancel running only)").option("--json","Output raw JSON response").action(async e=>{let t=await py(e.realm,{cancelPending:e.cancelPending});if(e.json)N.output(JSON.stringify(t,null,2)),t.ok||process.exit(1);else if(t.ok){let n=e.cancelPending?"running and pending":"running";console.log(`${S}Cancelled ${n} indexing jobs for ${e.realm}${f}`)}else console.error(`${h}Error:${f} ${t.error}`),process.exit(1)})}var hy=Object.freeze({a:"https://boxel-images.boxel.ai/icons/Letter-a.png",b:"https://boxel-images.boxel.ai/icons/Letter-b.png",c:"https://boxel-images.boxel.ai/icons/Letter-c.png",d:"https://boxel-images.boxel.ai/icons/Letter-d.png",e:"https://boxel-images.boxel.ai/icons/Letter-e.png",f:"https://boxel-images.boxel.ai/icons/Letter-f.png",g:"https://boxel-images.boxel.ai/icons/Letter-g.png",h:"https://boxel-images.boxel.ai/icons/Letter-h.png",i:"https://boxel-images.boxel.ai/icons/Letter-i.png",j:"https://boxel-images.boxel.ai/icons/Letter-j.png",k:"https://boxel-images.boxel.ai/icons/Letter-k.png",l:"https://boxel-images.boxel.ai/icons/Letter-l.png",m:"https://boxel-images.boxel.ai/icons/Letter-m.png",n:"https://boxel-images.boxel.ai/icons/Letter-n.png",o:"https://boxel-images.boxel.ai/icons/Letter-o.png",p:"https://boxel-images.boxel.ai/icons/Letter-p.png",q:"https://boxel-images.boxel.ai/icons/Letter-q.png",r:"https://boxel-images.boxel.ai/icons/Letter-r.png",s:"https://boxel-images.boxel.ai/icons/Letter-s.png",t:"https://boxel-images.boxel.ai/icons/Letter-t.png",u:"https://boxel-images.boxel.ai/icons/Letter-u.png",v:"https://boxel-images.boxel.ai/icons/Letter-v.png",w:"https://boxel-images.boxel.ai/icons/Letter-w.png",x:"https://boxel-images.boxel.ai/icons/Letter-x.png",y:"https://boxel-images.boxel.ai/icons/Letter-y.png",z:"https://boxel-images.boxel.ai/icons/letter-z.png"}),Cl=Object.freeze(["https://boxel-images.boxel.ai/background-images/4k-arabic-teal.jpg","https://boxel-images.boxel.ai/background-images/4k-arrow-weave.jpg","https://boxel-images.boxel.ai/background-images/4k-atmosphere-curvature.jpg","https://boxel-images.boxel.ai/background-images/4k-brushed-slabs.jpg","https://boxel-images.boxel.ai/background-images/4k-coral-reefs.jpg","https://boxel-images.boxel.ai/background-images/4k-crescent-lake.jpg","https://boxel-images.boxel.ai/background-images/4k-curvilinear-stairs.jpg","https://boxel-images.boxel.ai/background-images/4k-desert-dunes.jpg","https://boxel-images.boxel.ai/background-images/4k-doodle-board.jpg","https://boxel-images.boxel.ai/background-images/4k-fallen-leaves.jpg","https://boxel-images.boxel.ai/background-images/4k-flowing-mesh.jpg","https://boxel-images.boxel.ai/background-images/4k-glass-reflection.jpg","https://boxel-images.boxel.ai/background-images/4k-glow-cells.jpg","https://boxel-images.boxel.ai/background-images/4k-granite-peaks.jpg","https://boxel-images.boxel.ai/background-images/4k-green-wormhole.jpg","https://boxel-images.boxel.ai/background-images/4k-joshua-dawn.jpg","https://boxel-images.boxel.ai/background-images/4k-lava-river.jpg","https://boxel-images.boxel.ai/background-images/4k-leaves-moss.jpg","https://boxel-images.boxel.ai/background-images/4k-light-streaks.jpg","https://boxel-images.boxel.ai/background-images/4k-lowres-glitch.jpg","https://boxel-images.boxel.ai/background-images/4k-marble-shimmer.jpg","https://boxel-images.boxel.ai/background-images/4k-metallic-leather.jpg","https://boxel-images.boxel.ai/background-images/4k-microscopic-crystals.jpg","https://boxel-images.boxel.ai/background-images/4k-moon-face.jpg","https://boxel-images.boxel.ai/background-images/4k-mountain-runway.jpg","https://boxel-images.boxel.ai/background-images/4k-origami-flock.jpg","https://boxel-images.boxel.ai/background-images/4k-paint-swirl.jpg","https://boxel-images.boxel.ai/background-images/4k-pastel-triangles.jpg","https://boxel-images.boxel.ai/background-images/4k-perforated-sheet.jpg","https://boxel-images.boxel.ai/background-images/4k-plastic-ripples.jpg","https://boxel-images.boxel.ai/background-images/4k-powder-puff.jpg","https://boxel-images.boxel.ai/background-images/4k-radiant-crystal.jpg","https://boxel-images.boxel.ai/background-images/4k-redrock-canyon.jpg","https://boxel-images.boxel.ai/background-images/4k-rock-portal.jpg","https://boxel-images.boxel.ai/background-images/4k-rolling-hills.jpg","https://boxel-images.boxel.ai/background-images/4k-sand-stone.jpg","https://boxel-images.boxel.ai/background-images/4k-silver-fur.jpg","https://boxel-images.boxel.ai/background-images/4k-spa-pool.jpg","https://boxel-images.boxel.ai/background-images/4k-stained-glass.jpg","https://boxel-images.boxel.ai/background-images/4k-stone-veins.jpg","https://boxel-images.boxel.ai/background-images/4k-tangerine-plains.jpg","https://boxel-images.boxel.ai/background-images/4k-techno-floor.jpg","https://boxel-images.boxel.ai/background-images/4k-thick-frost.jpg","https://boxel-images.boxel.ai/background-images/4k-water-surface.jpg","https://boxel-images.boxel.ai/background-images/4k-watercolor-splashes.jpg","https://boxel-images.boxel.ai/background-images/4k-wildflower-field.jpg","https://boxel-images.boxel.ai/background-images/4k-wood-grain.jpg"]);function In(r){if(!r)return;let e=r.toLowerCase().replace(/[^a-z0-9]/g,"").replace(/^[0-9]+/,"");return hy[e.charAt(0)]}function Al(){let r=Math.floor(Math.random()*Cl.length);return Cl[r]}var gy=/^[a-z0-9-]+$/;function Tl(r){r.command("create").description("Create a new realm on the realm server").argument("<realm-name>","realm name (lowercase, numbers, hyphens only)").argument("<display-name>","display name for the realm").option("--background <url>","background image URL").option("--icon <url>","icon image URL").action(async(e,t,n)=>{await Ey(e,t,n)})}async function yy(r,e,t={}){let n=t.profileManager??A(),i=n.getActiveProfile();if(!i)throw new Error("No active profile. Run `boxel profile add` to create one.");let o=i.profile.realmServerUrl.replace(/\/$/,""),s={endpoint:r,name:e,backgroundURL:t.background??Al(),iconURL:t.icon??In(e)??In(r)},a=await n.authedRealmServerFetch(`${o}/_create-realm`,{method:"POST",headers:{"Content-Type":"application/vnd.api+json"},body:JSON.stringify({data:{type:"realm",attributes:s}})});if(!a.ok){let d;try{d=await a.text()}catch{d="server returned a non-serialized object body"}if(d.includes("[object Object]")&&(d="server returned a non-serialized object body"),d.includes("already exists")){let p=$y(d,o,r),w=await Pl(n,p);try{await n.addToUserRealms(p)}catch{}return{realmUrl:p,created:!1,realmToken:w}}throw new Error(`Realm server returned ${a.status}: ${d}`)}let u=(await a.json())?.data?.id;if(typeof u!="string"||u.trim()==="")throw new Error(`Realm server response did not include a realm URL (data.id) for "${r}".`);let c=P(u),m=await Pl(n,c);try{await n.addToUserRealms(c)}catch{}return t.waitForReady&&m&&await wy(c,m),{realmUrl:c,created:!0,realmToken:m}}async function Pl(r,e){try{let t=await r.getOrRefreshServerToken();return await r.fetchAndStoreRealmToken(e,t)}catch{return}}async function wy(r,e){let t=new URL("_readiness-check",r).href,n=15e3,i=250,o=Date.now(),s;for(;Date.now()-o<n;){try{let a=await fetch(t,{headers:{Accept:"application/vnd.api+json",Authorization:e}});if(a.ok)return;s=`HTTP ${a.status}`}catch(a){s=a instanceof Error?a.message:String(a)}await new Promise(a=>setTimeout(a,i))}throw new Error(`Timed out waiting for realm ${r} to become ready${s?`: ${s}`:""}`)}async function Ey(r,e,t){gy.test(r)||(console.error("Error: realm name must contain only lowercase letters, numbers, and hyphens"),process.exit(1));try{let n=await yy(r,e,t),i=n.created?"created":"already exists";console.log(`${S}Realm ${i}:${f} ${_}${n.realmUrl}${f}`)}catch(n){console.error(`Error: ${n instanceof Error?n.message:String(n)}`),process.exit(1)}}function $y(r,e,t){let n=r.match(/'(https?:\/\/[^']+)'/);if(n)return P(n[1]);throw new Error(`Could not determine realm URL from server error response for endpoint "${t}" on "${e}". The response did not include an explicit realm URL.`)}var st=O(require("fs"));var Bl=require("child_process"),X=O(require("fs/promises")),H=O(require("path"));var V=O(require("fs/promises")),G=O(require("path")),Hn=O(ql());var qn=class{value;next;constructor(e){this.value=e}},it=class{#e;#t;#r;constructor(){this.clear()}enqueue(e){let t=new qn(e);this.#e?(this.#t.next=t,this.#t=t):(this.#e=t,this.#t=t),this.#r++}dequeue(){let e=this.#e;if(e)return this.#e=this.#e.next,this.#r--,this.#e||(this.#t=void 0),e.value}peek(){if(this.#e)return this.#e.value}clear(){this.#e=void 0,this.#t=void 0,this.#r=0}get size(){return this.#r}*[Symbol.iterator](){let e=this.#e;for(;e;)yield e.value,e=e.next}*drain(){for(;this.#e;)yield this.dequeue()}};function Gn(r){let e=!1;if(typeof r=="object"&&({concurrency:r,rejectOnClear:e=!1}=r),Gl(r),typeof e!="boolean")throw new TypeError("Expected `rejectOnClear` to be a boolean");let t=new it,n=0,i=()=>{n<r&&t.size>0&&(n++,t.dequeue().run())},o=()=>{n--,i()},s=async(u,c,m)=>{let d=(async()=>u(...m))();c(d);try{await d}catch{}o()},a=(u,c,m,d)=>{let p={reject:m};new Promise(w=>{p.run=w,t.enqueue(p)}).then(s.bind(void 0,u,c,d)),n<r&&i()},l=(u,...c)=>new Promise((m,d)=>{a(u,m,d,c)});return Object.defineProperties(l,{activeCount:{get:()=>n},pendingCount:{get:()=>t.size},clearQueue:{value(){if(!e){t.clear();return}let u=AbortSignal.abort().reason;for(;t.size>0;)t.dequeue().reject(u)}},concurrency:{get:()=>r,set(u){Gl(u),r=u,queueMicrotask(()=>{for(;n<r&&t.size>0;)i()})}},map:{async value(u,c){let m=Array.from(u,(d,p)=>this(c,d,p));return Promise.all(m)}}}),l}function Gl(r){if(!((Number.isInteger(r)||r===Number.POSITIVE_INFINITY)&&r>0))throw new TypeError("Expected `concurrency` to be a number from 1 and up")}var Fy=Hn.default.default||Hn.default,Uy=new Set([".realm.json"]),Vn=1e4,jy=3e3;function D(r){let e=r.replace(/\\/g,"/").replace(/^\/+/,"");return Uy.has(e)}async function Vl(r){try{return await V.access(r),!0}catch{return!1}}function Hl(r){try{return decodeURIComponent(r)}catch{return r}}var ot={CardSource:"application/vnd.card+source",DirectoryListing:"application/vnd.api+json",Mtimes:"application/vnd.api+json"},qy=10,Wl=new Set(["node_modules"]),oe=class{constructor(e,t){this.options=e;this.authenticator=t;this.normalizedRealmUrl=this.normalizeRealmUrl(e.realmUrl)}normalizedRealmUrl;ignoreCache=new Map;remoteLimit=Gn(qy);normalizeRealmUrl(e){try{let t=new URL(e),n=t.pathname;return(n.split("/").filter(Boolean).pop()||"").includes(".")?console.warn(`Warning: "${e}" looks like a file URL, not a realm URL.
65
65
  Realm URLs should point to a directory (e.g., ${t.origin}${n.replace(/\/[^/]*\.[^/]*$/,"/")})`):e.endsWith("/")||console.warn(`Warning: Realm URL should end with a trailing slash.
66
- Did you mean "${e}/"?`),t.href.replace(/\/+$/,"")+"/"}catch{throw new Error(`Invalid workspace URL: ${e}`)}}buildDirectoryUrl(e=""){if(!e)return this.normalizedRealmUrl;let t=e.replace(/^\/+|\/+$/g,"");return`${this.normalizedRealmUrl}${t}/`}buildFileUrl(e){let t=e.replace(/^\/+/,"");return`${this.normalizedRealmUrl}${t}`}async getRemoteFileList(e=""){let t=new Map;try{let n=this.buildDirectoryUrl(e),i=await this.remoteLimit(()=>this.authenticator.authedRealmFetch(n,{headers:{Accept:"application/vnd.api+json"}}));if(!i.ok){if(i.status===404)return t;throw i.status===401||i.status===403?new Error(`Authentication failed (${i.status}): Cannot access workspace. Check your Matrix credentials and workspace permissions.`):new Error(`Failed to get directory listing: ${i.status} ${i.statusText}`)}let o=await i.json();if(o.data&&o.data.relationships){let s=Object.entries(o.data.relationships),a=await Promise.all(s.map(([l,u])=>{let m=u.meta.kind==="file",d=e?G.posix.join(e,l):l;return m?this.shouldIgnoreRemoteFile(d)?[]:[[d,!0]]:(async()=>{let p=await this.getRemoteFileList(d);return Array.from(p.entries())})()}));for(let l of a)for(let[u,c]of l)t.set(u,c)}}catch(n){throw n instanceof Error&&(n.message.includes("Authentication failed")||n.message.includes("Cannot access workspace")||n.message.includes("401")||n.message.includes("403"))||console.error(`Error reading remote directory ${e}:`,n),n}return t}async getRemoteMtimes(){let e=new Map;try{let t=`${this.normalizedRealmUrl}_mtimes`,n=await this.authenticator.authedRealmFetch(t,{headers:{Accept:it.Mtimes}});if(!n.ok){if(n.status===404)return console.log("Note: _mtimes endpoint not available, will upload all files"),e;throw new Error(`Failed to get mtimes: ${n.status} ${n.statusText}`)}let i=await n.json();if(i.data?.attributes?.mtimes){let o=Object.entries(i.data.attributes.mtimes);process.env.DEBUG&&(console.log(`Remote mtimes received: ${o.length} entries`),o.length>0&&console.log(`Sample: ${o[0][0]} = ${o[0][1]}`));for(let[s,a]of o){let l=s.replace(this.normalizedRealmUrl,""),u;try{u=decodeURIComponent(l)}catch{u=l}this.shouldIgnoreRemoteFile(u)||e.set(u,a)}}else process.env.DEBUG&&console.log("No mtimes in response:",JSON.stringify(i).slice(0,200))}catch(t){console.warn("Could not fetch remote mtimes, will upload all files:",t)}return e}async getLocalFileListWithMtimes(e=""){let t=new Map,n=G.join(this.options.localDir,e),i;try{i=await V.readdir(n,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")return t;throw s}let o=await Promise.all(i.map(async s=>{let a=G.join(n,s.name),l=e?G.posix.join(e,s.name):s.name;if(s.isDirectory()&&Wl.has(s.name))return[];if(await this.shouldIgnoreFile(l,a))return[];if(s.isFile()){let u=await V.stat(a);return[[l,{path:a,mtime:u.mtimeMs}]]}else if(s.isDirectory()){let u=await this.getLocalFileListWithMtimes(l);return Array.from(u.entries())}return[]}));for(let s of o)for(let[a,l]of s)t.set(a,l);return t}async getLocalFileList(e=""){let t=new Map,n=G.join(this.options.localDir,e),i;try{i=await V.readdir(n,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")return t;throw s}let o=await Promise.all(i.map(async s=>{let a=G.join(n,s.name),l=e?G.posix.join(e,s.name):s.name;if(s.isDirectory()&&Wl.has(s.name))return[];if(await this.shouldIgnoreFile(l,a))return[];if(s.isFile())return[[l,a]];if(s.isDirectory()){let u=await this.getLocalFileList(l);return Array.from(u.entries())}return[]}));for(let s of o)for(let[a,l]of s)t.set(a,l);return t}async uploadFile(e,t){if(D(e)){console.log(` Skipped (protected): ${e}`);return}if(console.log(`Uploading: ${e}`),this.options.dryRun){console.log(`[DRY RUN] Would upload ${e}`);return}let n=await V.readFile(t,"utf8"),i=this.buildFileUrl(e),o=await this.authenticator.authedRealmFetch(i,{method:"POST",headers:{"Content-Type":"text/plain;charset=UTF-8",Accept:it.CardSource},body:n});if(!o.ok)throw new Error(`Failed to upload: ${o.status} ${o.statusText}`);console.log(` Uploaded: ${e}`)}async uploadFilesAtomic(e,t){let n=Array.from(e.entries()).filter(([u])=>!D(u));if(n.length===0)return{succeeded:[]};if(this.options.dryRun){for(let[u]of n)console.log(`[DRY RUN] Would upload ${u}`);return{succeeded:[]}}let i=await Promise.all(n.map(async([u,c])=>{let m=await V.readFile(c,"utf8");return{op:t.has(u)?"add":"update",href:this.buildFileUrl(u),data:{type:"source",attributes:{content:m},meta:{}}}})),o=this.options.waitForIndex?`${this.normalizedRealmUrl}_atomic?waitForIndex=true`:`${this.normalizedRealmUrl}_atomic`,s=await this.authenticator.authedRealmFetch(o,{method:"POST",headers:{"Content-Type":"application/vnd.api+json",Accept:"application/vnd.api+json"},body:JSON.stringify({"atomic:operations":i})});if(s.status===201){let u=await s.json(),c=new Map(n.map(([d])=>[this.buildFileUrl(d),d])),m=(u["atomic:results"]??[]).map(d=>d.data?.id).filter(d=>typeof d=="string").map(d=>Hl(d)).map(d=>c.get(d)??d);for(let d of m)console.log(` Uploaded: ${d}`);return{succeeded:m}}let a={};try{a=await s.json()}catch{}let l=(a.errors??[]).map(u=>{let m=(u.detail??"").match(/Resource (\S+) /),d=m?Hl(m[1]):"";return{path:new Map(n.map(([w])=>[this.buildFileUrl(w),w])).get(d)??d,status:u.status??s.status,title:u.title??"Error"}});return{succeeded:[],error:{status:s.status,perFile:l,message:`Atomic upload failed: ${s.status} ${s.statusText}`}}}async downloadFile(e,t){if(console.log(`Downloading: ${e}`),this.options.dryRun){console.log(`[DRY RUN] Would download ${e}`);return}let n=this.buildFileUrl(e),i=await this.authenticator.authedRealmFetch(n,{headers:{Accept:it.CardSource}});if(!i.ok)throw new Error(`Failed to download: ${i.status} ${i.statusText}`);let o=await i.text(),s=G.dirname(t);await V.mkdir(s,{recursive:!0}),await V.writeFile(t,o,"utf8"),console.log(` Downloaded: ${e}`)}async deleteFile(e){if(D(e)){console.log(` Skipped (protected): ${e}`);return}if(console.log(`Deleting remote: ${e}`),this.options.dryRun){console.log(`[DRY RUN] Would delete ${e}`);return}let t=this.buildFileUrl(e),n=Date.now(),i;try{i=await this.authenticator.authedRealmFetch(t,{method:"DELETE",headers:{Accept:it.CardSource},signal:AbortSignal.timeout(Gn)})}catch(s){let a=Date.now()-n;if(console.error(` Delete request failed after ${a}ms: ${e}`),s instanceof Error&&(s.name==="TimeoutError"||s.name==="AbortError")){if(await this.verifyDeleteApplied(e)===!0){console.warn(` Delete response timed out after ${Gn}ms, but ${e} is already gone on the realm; continuing`);return}throw new Error(`Timed out deleting ${e} after ${Gn}ms`,{cause:s})}throw s}let o=Date.now()-n;if(console.log(` Delete response for ${e}: ${i.status} ${i.statusText} (${o}ms)`),!i.ok&&i.status!==404)throw new Error(`Failed to delete: ${i.status} ${i.statusText}`);console.log(` Deleted: ${e}`)}async verifyDeleteApplied(e){let t=this.buildFileUrl(e);try{let n=await this.authenticator.authedRealmFetch(t,{headers:{Accept:it.CardSource},signal:AbortSignal.timeout(jy)});return console.warn(` Delete-timeout probe for ${e}: ${n.status} ${n.statusText}`),n.status===404}catch(n){return console.warn(` Delete-timeout probe failed for ${e}:`,n),"unknown"}}async deleteLocalFile(e){if(console.log(`Deleting local: ${e}`),this.options.dryRun){console.log(`[DRY RUN] Would delete local file ${e}`);return}try{await V.unlink(e),console.log(` Deleted: ${e}`)}catch(t){if(t.code!=="ENOENT")throw t}}getIgnoreInstance(e){let t=this.ignoreCache.get(e);if(t)return t;let n=(async()=>{let i=Fy(),o=e,s=this.options.localDir;for(;o.startsWith(s);){let a=G.join(o,".gitignore");if(await Vl(a))try{let c=await V.readFile(a,"utf8");i.add(c)}catch(c){console.warn(`Warning: Could not read .gitignore file at ${a}:`,c)}let l=G.join(o,".boxelignore");if(await Vl(l))try{let c=await V.readFile(l,"utf8");i.add(c)}catch(c){console.warn(`Warning: Could not read .boxelignore file at ${l}:`,c)}let u=G.dirname(o);if(u===o)break;o=u}return i})();return this.ignoreCache.set(e,n),n}async shouldIgnoreFile(e,t){let n=G.basename(e);if(n===".boxel-sync.json"||n.startsWith("."))return!0;let i=G.dirname(t),o=await this.getIgnoreInstance(i),s=e.replace(/\\/g,"/");return o.ignores(s)}shouldIgnoreRemoteFile(e){return!!G.basename(e).startsWith(".")}};async function Hn(r){try{return await Y.access(r),!0}catch{return!1}}var U=class{workspaceDir;gitDir;constructor(e){this.workspaceDir=H.resolve(e),this.gitDir=H.join(this.workspaceDir,".boxel-history")}async init(){await Hn(this.gitDir)||await Y.mkdir(this.gitDir,{recursive:!0});let e=H.join(this.gitDir,".git");await Hn(e)||(await this.git("init"),await this.git("config","user.email","boxel-cli@local"),await this.git("config","user.name","Boxel CLI"),await this.git("commit","--allow-empty","-m","[init] Initialize checkpoint history"))}async isInitialized(){return Hn(H.join(this.gitDir,".git"))}async syncFilesToHistory(){let e=await this.getWorkspaceFiles(),t=new Set(e),n=await this.getHistoryFiles();await Promise.all(n.map(async i=>{if(!t.has(i)){let o=H.join(this.gitDir,i);try{await Y.unlink(o)}catch(s){if(s.code!=="ENOENT")throw s}}})),await Promise.all(e.map(async i=>{let o=H.join(this.workspaceDir,i),s=H.join(this.gitDir,i),a=H.dirname(s);await Y.mkdir(a,{recursive:!0}),await Y.copyFile(o,s)}))}async getWorkspaceFiles(){let e=[],t=async(n,i="")=>{let o;try{o=await Y.readdir(n,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")return;throw s}await Promise.all(o.map(async s=>{if(s.name===".boxel-history"||s.name===".boxel-sync.json"||s.name==="node_modules"||s.name.startsWith("."))return;let a=i?`${i}/${s.name}`:s.name;s.isDirectory()?await t(H.join(n,s.name),a):e.push(a)}))};return await t(this.workspaceDir),e}async getHistoryFiles(){let e=[],t=async(n,i="")=>{let o;try{o=await Y.readdir(n,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")return;throw s}await Promise.all(o.map(async s=>{if(s.name===".git")return;let a=i?`${i}/${s.name}`:s.name;s.isDirectory()?await t(H.join(n,s.name),a):e.push(a)}))};return await t(this.gitDir),e}async detectCurrentChanges(){if(!await this.isInitialized())return(await this.getWorkspaceFiles()).map(i=>({file:i,status:"added"}));await this.syncFilesToHistory();let e=(await this.git("status","--porcelain")).replace(/\n+$/,"");if(!e)return[];let t=[];for(let n of e.split(`
66
+ Did you mean "${e}/"?`),t.href.replace(/\/+$/,"")+"/"}catch{throw new Error(`Invalid workspace URL: ${e}`)}}buildDirectoryUrl(e=""){if(!e)return this.normalizedRealmUrl;let t=e.replace(/^\/+|\/+$/g,"");return`${this.normalizedRealmUrl}${t}/`}buildFileUrl(e){let t=e.replace(/^\/+/,"");return`${this.normalizedRealmUrl}${t}`}async getRemoteFileList(e=""){let t=new Map;try{let n=this.buildDirectoryUrl(e),i=await this.remoteLimit(()=>this.authenticator.authedRealmFetch(n,{headers:{Accept:"application/vnd.api+json"}}));if(!i.ok){if(i.status===404)return t;throw i.status===401||i.status===403?new Error(`Authentication failed (${i.status}): Cannot access workspace. Check your Matrix credentials and workspace permissions.`):new Error(`Failed to get directory listing: ${i.status} ${i.statusText}`)}let o=await i.json();if(o.data&&o.data.relationships){let s=Object.entries(o.data.relationships),a=await Promise.all(s.map(([l,u])=>{let m=u.meta.kind==="file",d=e?G.posix.join(e,l):l;return m?this.shouldIgnoreRemoteFile(d)?[]:[[d,!0]]:(async()=>{let p=await this.getRemoteFileList(d);return Array.from(p.entries())})()}));for(let l of a)for(let[u,c]of l)t.set(u,c)}}catch(n){throw n instanceof Error&&(n.message.includes("Authentication failed")||n.message.includes("Cannot access workspace")||n.message.includes("401")||n.message.includes("403"))||console.error(`Error reading remote directory ${e}:`,n),n}return t}async getRemoteMtimes(){let e=new Map;try{let t=`${this.normalizedRealmUrl}_mtimes`,n=await this.authenticator.authedRealmFetch(t,{headers:{Accept:ot.Mtimes}});if(!n.ok){if(n.status===404)return console.log("Note: _mtimes endpoint not available, will upload all files"),e;throw new Error(`Failed to get mtimes: ${n.status} ${n.statusText}`)}let i=await n.json();if(i.data?.attributes?.mtimes){let o=Object.entries(i.data.attributes.mtimes);process.env.DEBUG&&(console.log(`Remote mtimes received: ${o.length} entries`),o.length>0&&console.log(`Sample: ${o[0][0]} = ${o[0][1]}`));for(let[s,a]of o){let l=s.replace(this.normalizedRealmUrl,""),u;try{u=decodeURIComponent(l)}catch{u=l}this.shouldIgnoreRemoteFile(u)||e.set(u,a)}}else process.env.DEBUG&&console.log("No mtimes in response:",JSON.stringify(i).slice(0,200))}catch(t){console.warn("Could not fetch remote mtimes, will upload all files:",t)}return e}async getLocalFileListWithMtimes(e=""){let t=new Map,n=G.join(this.options.localDir,e),i;try{i=await V.readdir(n,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")return t;throw s}let o=await Promise.all(i.map(async s=>{let a=G.join(n,s.name),l=e?G.posix.join(e,s.name):s.name;if(s.isDirectory()&&Wl.has(s.name))return[];if(await this.shouldIgnoreFile(l,a))return[];if(s.isFile()){let u=await V.stat(a);return[[l,{path:a,mtime:u.mtimeMs}]]}else if(s.isDirectory()){let u=await this.getLocalFileListWithMtimes(l);return Array.from(u.entries())}return[]}));for(let s of o)for(let[a,l]of s)t.set(a,l);return t}async getLocalFileList(e=""){let t=new Map,n=G.join(this.options.localDir,e),i;try{i=await V.readdir(n,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")return t;throw s}let o=await Promise.all(i.map(async s=>{let a=G.join(n,s.name),l=e?G.posix.join(e,s.name):s.name;if(s.isDirectory()&&Wl.has(s.name))return[];if(await this.shouldIgnoreFile(l,a))return[];if(s.isFile())return[[l,a]];if(s.isDirectory()){let u=await this.getLocalFileList(l);return Array.from(u.entries())}return[]}));for(let s of o)for(let[a,l]of s)t.set(a,l);return t}async uploadFile(e,t){if(D(e)){console.log(` Skipped (protected): ${e}`);return}if(console.log(`Uploading: ${e}`),this.options.dryRun){console.log(`[DRY RUN] Would upload ${e}`);return}let n=await V.readFile(t,"utf8"),i=this.buildFileUrl(e),o=await this.authenticator.authedRealmFetch(i,{method:"POST",headers:{"Content-Type":"text/plain;charset=UTF-8",Accept:ot.CardSource},body:n});if(!o.ok)throw new Error(`Failed to upload: ${o.status} ${o.statusText}`);console.log(` Uploaded: ${e}`)}async uploadFilesAtomic(e,t){let n=Array.from(e.entries()).filter(([u])=>!D(u));if(n.length===0)return{succeeded:[]};if(this.options.dryRun){for(let[u]of n)console.log(`[DRY RUN] Would upload ${u}`);return{succeeded:[]}}let i=await Promise.all(n.map(async([u,c])=>{let m=await V.readFile(c,"utf8");return{op:t.has(u)?"add":"update",href:this.buildFileUrl(u),data:{type:"source",attributes:{content:m},meta:{}}}})),o=this.options.waitForIndex?`${this.normalizedRealmUrl}_atomic?waitForIndex=true`:`${this.normalizedRealmUrl}_atomic`,s=await this.authenticator.authedRealmFetch(o,{method:"POST",headers:{"Content-Type":"application/vnd.api+json",Accept:"application/vnd.api+json"},body:JSON.stringify({"atomic:operations":i})});if(s.status===201){let u=await s.json(),c=new Map(n.map(([d])=>[this.buildFileUrl(d),d])),m=(u["atomic:results"]??[]).map(d=>d.data?.id).filter(d=>typeof d=="string").map(d=>Hl(d)).map(d=>c.get(d)??d);for(let d of m)console.log(` Uploaded: ${d}`);return{succeeded:m}}let a={};try{a=await s.json()}catch{}let l=(a.errors??[]).map(u=>{let m=(u.detail??"").match(/Resource (\S+) /),d=m?Hl(m[1]):"";return{path:new Map(n.map(([w])=>[this.buildFileUrl(w),w])).get(d)??d,status:u.status??s.status,title:u.title??"Error"}});return{succeeded:[],error:{status:s.status,perFile:l,message:`Atomic upload failed: ${s.status} ${s.statusText}`}}}async downloadFile(e,t){if(console.log(`Downloading: ${e}`),this.options.dryRun){console.log(`[DRY RUN] Would download ${e}`);return}let n=this.buildFileUrl(e),i=await this.authenticator.authedRealmFetch(n,{headers:{Accept:ot.CardSource}});if(!i.ok)throw new Error(`Failed to download: ${i.status} ${i.statusText}`);let o=await i.text(),s=G.dirname(t);await V.mkdir(s,{recursive:!0}),await V.writeFile(t,o,"utf8"),console.log(` Downloaded: ${e}`)}async deleteFile(e){if(D(e)){console.log(` Skipped (protected): ${e}`);return}if(console.log(`Deleting remote: ${e}`),this.options.dryRun){console.log(`[DRY RUN] Would delete ${e}`);return}let t=this.buildFileUrl(e),n=Date.now(),i;try{i=await this.authenticator.authedRealmFetch(t,{method:"DELETE",headers:{Accept:ot.CardSource},signal:AbortSignal.timeout(Vn)})}catch(s){let a=Date.now()-n;if(console.error(` Delete request failed after ${a}ms: ${e}`),s instanceof Error&&(s.name==="TimeoutError"||s.name==="AbortError")){if(await this.verifyDeleteApplied(e)===!0){console.warn(` Delete response timed out after ${Vn}ms, but ${e} is already gone on the realm; continuing`);return}throw new Error(`Timed out deleting ${e} after ${Vn}ms`,{cause:s})}throw s}let o=Date.now()-n;if(console.log(` Delete response for ${e}: ${i.status} ${i.statusText} (${o}ms)`),!i.ok&&i.status!==404)throw new Error(`Failed to delete: ${i.status} ${i.statusText}`);console.log(` Deleted: ${e}`)}async verifyDeleteApplied(e){let t=this.buildFileUrl(e);try{let n=await this.authenticator.authedRealmFetch(t,{headers:{Accept:ot.CardSource},signal:AbortSignal.timeout(jy)});return console.warn(` Delete-timeout probe for ${e}: ${n.status} ${n.statusText}`),n.status===404}catch(n){return console.warn(` Delete-timeout probe failed for ${e}:`,n),"unknown"}}async deleteLocalFile(e){if(console.log(`Deleting local: ${e}`),this.options.dryRun){console.log(`[DRY RUN] Would delete local file ${e}`);return}try{await V.unlink(e),console.log(` Deleted: ${e}`)}catch(t){if(t.code!=="ENOENT")throw t}}getIgnoreInstance(e){let t=this.ignoreCache.get(e);if(t)return t;let n=(async()=>{let i=Fy(),o=e,s=this.options.localDir;for(;o.startsWith(s);){let a=G.join(o,".gitignore");if(await Vl(a))try{let c=await V.readFile(a,"utf8");i.add(c)}catch(c){console.warn(`Warning: Could not read .gitignore file at ${a}:`,c)}let l=G.join(o,".boxelignore");if(await Vl(l))try{let c=await V.readFile(l,"utf8");i.add(c)}catch(c){console.warn(`Warning: Could not read .boxelignore file at ${l}:`,c)}let u=G.dirname(o);if(u===o)break;o=u}return i})();return this.ignoreCache.set(e,n),n}async shouldIgnoreFile(e,t){let n=G.basename(e);if(n===".boxel-sync.json"||n.startsWith("."))return!0;let i=G.dirname(t),o=await this.getIgnoreInstance(i),s=e.replace(/\\/g,"/");return o.ignores(s)}shouldIgnoreRemoteFile(e){return!!G.basename(e).startsWith(".")}};async function Wn(r){try{return await X.access(r),!0}catch{return!1}}var U=class{workspaceDir;gitDir;constructor(e){this.workspaceDir=H.resolve(e),this.gitDir=H.join(this.workspaceDir,".boxel-history")}async init(){await Wn(this.gitDir)||await X.mkdir(this.gitDir,{recursive:!0});let e=H.join(this.gitDir,".git");await Wn(e)||(await this.git("init"),await this.git("config","user.email","boxel-cli@local"),await this.git("config","user.name","Boxel CLI"),await this.git("commit","--allow-empty","-m","[init] Initialize checkpoint history"))}async isInitialized(){return Wn(H.join(this.gitDir,".git"))}async syncFilesToHistory(){let e=await this.getWorkspaceFiles(),t=new Set(e),n=await this.getHistoryFiles();await Promise.all(n.map(async i=>{if(!t.has(i)){let o=H.join(this.gitDir,i);try{await X.unlink(o)}catch(s){if(s.code!=="ENOENT")throw s}}})),await Promise.all(e.map(async i=>{let o=H.join(this.workspaceDir,i),s=H.join(this.gitDir,i),a=H.dirname(s);await X.mkdir(a,{recursive:!0}),await X.copyFile(o,s)}))}async getWorkspaceFiles(){let e=[],t=async(n,i="")=>{let o;try{o=await X.readdir(n,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")return;throw s}await Promise.all(o.map(async s=>{if(s.name===".boxel-history"||s.name===".boxel-sync.json"||s.name==="node_modules"||s.name.startsWith("."))return;let a=i?`${i}/${s.name}`:s.name;s.isDirectory()?await t(H.join(n,s.name),a):e.push(a)}))};return await t(this.workspaceDir),e}async getHistoryFiles(){let e=[],t=async(n,i="")=>{let o;try{o=await X.readdir(n,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")return;throw s}await Promise.all(o.map(async s=>{if(s.name===".git")return;let a=i?`${i}/${s.name}`:s.name;s.isDirectory()?await t(H.join(n,s.name),a):e.push(a)}))};return await t(this.gitDir),e}async detectCurrentChanges(){if(!await this.isInitialized())return(await this.getWorkspaceFiles()).map(i=>({file:i,status:"added"}));await this.syncFilesToHistory();let e=(await this.git("status","--porcelain")).replace(/\n+$/,"");if(!e)return[];let t=[];for(let n of e.split(`
67
67
  `)){if(!n)continue;let i=n.substring(0,2),o=n.substring(3);if(i.includes("R")){let s=o.indexOf(" -> ");if(s!==-1){let a=o.substring(0,s),l=o.substring(s+4);t.push({file:a,status:"deleted"}),t.push({file:l,status:"added"});continue}}i.includes("D")?t.push({file:o,status:"deleted"}):i.includes("A")||i.includes("C")||i==="??"?t.push({file:o,status:"added"}):(i.includes("M")||i.includes("U")||i.includes("T"))&&t.push({file:o,status:"modified"})}return t}async createCheckpoint(e,t,n){if(await this.isInitialized()||await this.init(),await this.syncFilesToHistory(),await this.git("add","-A"),!(await this.git("status","--porcelain")).trim())return null;let o=this.classifyChanges(t),{message:s,description:a}=n?{message:n,description:""}:this.generateCommitMessage(e,t,o),l=o?"[MAJOR]":"[minor]",u=`[${e}]`,c=`${l} ${u} ${s}${a?`
68
68
 
69
69
  `+a:""}`;await this.git("commit","-m",c);let m=(await this.git("rev-parse","HEAD")).trim(),d=m.substring(0,7);return{hash:m,shortHash:d,message:s,description:a,date:new Date,isMajor:o,filesChanged:t.length,insertions:0,deletions:0,source:e,isMilestone:!1}}classifyChanges(e){if(e.length>3)return!0;for(let t of e)if(t.status==="added"||t.status==="deleted"||t.file.endsWith(".gts"))return!0;return!1}generateCommitMessage(e,t,n){let i=e==="local"?"Push":e==="remote"?"Pull":"Manual";if(t.length===0)return{message:`${i}: No changes detected`,description:""};if(t.length===1){let m=t[0],d=m.status==="added"?"Add":m.status==="deleted"?"Delete":"Update";return{message:`${i}: ${d} ${m.file}`,description:""}}let o=t.filter(m=>m.status==="added"),s=t.filter(m=>m.status==="modified"),a=t.filter(m=>m.status==="deleted"),l=[];o.length>0&&l.push(`+${o.length}`),s.length>0&&l.push(`~${s.length}`),a.length>0&&l.push(`-${a.length}`);let u=`${i}: ${t.length} files (${l.join(", ")})`,c=[];return o.length>0&&(c.push("Added:"),o.forEach(m=>c.push(` + ${m.file}`))),s.length>0&&(c.push("Modified:"),s.forEach(m=>c.push(` ~ ${m.file}`))),a.length>0&&(c.push("Deleted:"),a.forEach(m=>c.push(` - ${m.file}`))),{message:u,description:c.join(`
70
70
  `)}}async getCheckpoints(e=50){if(!await this.isInitialized())return[];let n=await this.git("log","--format=%H|%h|%s|%aI|%an",`-${e}`);if(!n.trim())return[];let i=await this.getAllMilestones(),o=n.trim().split(`
71
71
  `).filter(s=>!(s.split("|")[2]??"").startsWith("[init]"));return Promise.all(o.map(s=>this.parseCheckpointLine(s,i)))}async parseCheckpointLine(e,t){let[n,i,o,s]=e.split("|"),a=o.includes("[MAJOR]"),l=o.includes("[local]")?"local":o.includes("[remote]")?"remote":"manual",u=o.replace(/\[(MAJOR|minor)\]\s*/i,"").replace(/\[(local|remote|manual)\]\s*/i,""),c=await this.getCommitStats(n),m=t.get(n),d=!!m;return{hash:n,shortHash:i,message:u,description:"",date:new Date(s),isMajor:a,source:l,isMilestone:d,milestoneName:m,...c}}async getCommitStats(e){try{let n=(await this.git("show","--stat","--format=",e)).trim().split(`
72
72
  `),i=n[n.length-1]||"",o=i.match(/(\d+) files? changed/),s=i.match(/(\d+) insertions?/),a=i.match(/(\d+) deletions?/);return{filesChanged:o?parseInt(o[1]):0,insertions:s?parseInt(s[1]):0,deletions:a?parseInt(a[1]):0}}catch{return{filesChanged:0,insertions:0,deletions:0}}}async getChangedFiles(e){return(await this.git("show","--name-only","--format=",e)).trim().split(`
73
- `).filter(Boolean)}async getDiff(e){return this.git("show","--format=",e)}async restore(e){let t=await this.getHistoryFiles();await Promise.all(t.map(async s=>{let a=H.join(this.gitDir,s);try{await Y.unlink(a)}catch(l){if(l.code!=="ENOENT")throw l}})),await this.git("checkout",e,"--",".");let n=await this.getHistoryFiles(),i=new Set(n),o=await this.getWorkspaceFiles();await Promise.all(o.map(async s=>{if(!D(s)&&!i.has(s)){let a=H.join(this.workspaceDir,s);try{await Y.unlink(a)}catch(l){if(l.code!=="ENOENT")throw l}}})),await Promise.all(n.map(async s=>{if(D(s))return;let a=H.join(this.gitDir,s),l=H.join(this.workspaceDir,s),u=H.dirname(l);await Y.mkdir(u,{recursive:!0}),await Y.copyFile(a,l)})),await this.git("checkout","HEAD","--",".")}async markMilestone(e,t){if(!await this.isInitialized())return null;let n;if(typeof e=="number"){let o=await this.getCheckpoints(e+1);if(e<1||e>o.length)return null;n=o[e-1].hash}else n=e;let i=`milestone/${t.replace(/\s+/g,"-").replace(/[^a-zA-Z0-9\-_.]/g,"")}`;try{return await this.git("tag","-a",i,n,"-m",`Milestone: ${t}`),{hash:n,name:t}}catch{return null}}async unmarkMilestone(e){if(!await this.isInitialized())return!1;let t;if(typeof e=="number"){let i=await this.getCheckpoints(e+1);if(e<1||e>i.length)return!1;t=i[e-1].hash}else t=e;let n=await this.getMilestoneTags(t);if(n.length===0)return!1;for(let i of n)try{await this.git("tag","-d",i)}catch{}return!0}async getMilestoneTags(e){try{return(await this.git("tag","--points-at",e)).trim().split(`
73
+ `).filter(Boolean)}async getDiff(e){return this.git("show","--format=",e)}async restore(e){let t=await this.getHistoryFiles();await Promise.all(t.map(async s=>{let a=H.join(this.gitDir,s);try{await X.unlink(a)}catch(l){if(l.code!=="ENOENT")throw l}})),await this.git("checkout",e,"--",".");let n=await this.getHistoryFiles(),i=new Set(n),o=await this.getWorkspaceFiles();await Promise.all(o.map(async s=>{if(!D(s)&&!i.has(s)){let a=H.join(this.workspaceDir,s);try{await X.unlink(a)}catch(l){if(l.code!=="ENOENT")throw l}}})),await Promise.all(n.map(async s=>{if(D(s))return;let a=H.join(this.gitDir,s),l=H.join(this.workspaceDir,s),u=H.dirname(l);await X.mkdir(u,{recursive:!0}),await X.copyFile(a,l)})),await this.git("checkout","HEAD","--",".")}async markMilestone(e,t){if(!await this.isInitialized())return null;let n;if(typeof e=="number"){let o=await this.getCheckpoints(e+1);if(e<1||e>o.length)return null;n=o[e-1].hash}else n=e;let i=`milestone/${t.replace(/\s+/g,"-").replace(/[^a-zA-Z0-9\-_.]/g,"")}`;try{return await this.git("tag","-a",i,n,"-m",`Milestone: ${t}`),{hash:n,name:t}}catch{return null}}async unmarkMilestone(e){if(!await this.isInitialized())return!1;let t;if(typeof e=="number"){let i=await this.getCheckpoints(e+1);if(e<1||e>i.length)return!1;t=i[e-1].hash}else t=e;let n=await this.getMilestoneTags(t);if(n.length===0)return!1;for(let i of n)try{await this.git("tag","-d",i)}catch{}return!0}async getMilestoneTags(e){try{return(await this.git("tag","--points-at",e)).trim().split(`
74
74
  `).filter(n=>n.startsWith("milestone/")).filter(Boolean)}catch{return[]}}async getAllMilestones(){let e=new Map;try{let t=await this.git("tag","-l","milestone/*");for(let n of t.trim().split(`
75
75
  `).filter(Boolean))try{let i=(await this.git("rev-list","-1",n)).trim(),o=n.replace("milestone/","").replace(/-/g," ");e.set(i,o)}catch{}}catch{}return e}async getMilestones(){if(!await this.isInitialized())return[];let e=await this.getAllMilestones();if(e.size===0)return[];let n=await this.git("log","--no-walk","--format=%H|%h|%s|%aI|%an",...e.keys());return n.trim()?Promise.all(n.trim().split(`
76
- `).map(i=>this.parseCheckpointLine(i,e))):[]}git(...e){return new Promise((t,n)=>{let i=(0,Bl.spawn)("git",e,{cwd:this.gitDir}),o="",s="";i.stdout.on("data",a=>{o+=a.toString("utf-8")}),i.stderr.on("data",a=>{s+=a.toString("utf-8")}),i.on("error",a=>n(a)),i.on("close",a=>{if(a!==0&&!e.includes("status")){n(new Error(`git ${e.join(" ")} failed: ${s}`));return}t(o)})})}};function rr(r,e){let t=r.trim();if(t==="")return{kind:"none"};if(t.length===7){let i=e.filter(o=>o.shortHash===t);if(i.length===1)return{kind:"found",target:i[0]};if(i.length>1)return{kind:"ambiguous",matches:i}}if(/^\d+$/.test(t)){let i=parseInt(t,10);return i>=1&&i<=e.length?{kind:"found",target:e[i-1]}:{kind:"none"}}let n=e.filter(i=>i.hash.startsWith(t));return n.length===0?{kind:"none"}:n.length===1?{kind:"found",target:n[0]}:{kind:"ambiguous",matches:n}}var Yl=100;function nr(r){return r instanceof Error?r.message:String(r)}async function Gy(r,e){if(!ot.existsSync(r))return{ok:!1,error:`Directory not found: ${r}`};try{let t=new U(r);if(!await t.isInitialized())return{ok:!0,checkpoints:[],truncated:!1};let n=await t.getCheckpoints(e+1),i=n.length>e;return{ok:!0,checkpoints:i?n.slice(0,e):n,truncated:i}}catch(t){return{ok:!1,error:`Failed to read checkpoint history: ${nr(t)}`}}}async function Vy(r,e){if(!ot.existsSync(r))return{ok:!1,error:`Directory not found: ${r}`};let t=e.trim();if(!t)return{ok:!1,error:"--message must not be empty."};try{let n=new U(r);await n.isInitialized()||await n.init();let i=await n.detectCurrentChanges(),o=await n.createCheckpoint("manual",i,t);return o?{ok:!0,created:o}:{ok:!1,error:"No changes to checkpoint."}}catch(n){return{ok:!1,error:`Failed to create checkpoint: ${nr(n)}`}}}async function Hy(r,e,t){if(!ot.existsSync(r))return{ok:!1,error:`Directory not found: ${r}`};try{let n=new U(r);if(!await n.isInitialized())return{ok:!1,error:"No checkpoint history found for this workspace. Checkpoints are created automatically during sync operations."};let i=await n.getCheckpoints(t),o=rr(e,i);if(o.kind==="none")return{ok:!1,error:`Checkpoint not found: ${e}. Use a number (1-${i.length}) or a commit hash.`};if(o.kind==="ambiguous"){let s=o.matches.slice(0,5).map(l=>l.shortHash).join(", "),a=o.matches.length>5?", \u2026":"";return{ok:!1,error:`Ambiguous reference: ${e} matches ${o.matches.length} checkpoints (${s}${a}). Use a longer prefix or full hash.`}}return{ok:!0,target:o.target}}catch(n){return{ok:!1,error:`Failed to read checkpoint history: ${nr(n)}`}}}async function Wy(r,e){if(!ot.existsSync(r))return{ok:!1,error:`Directory not found: ${r}`};try{let t=new U(r);return await t.isInitialized()?(await t.restore(e),{ok:!0}):{ok:!1,error:"No checkpoint history found for this workspace."}}catch(t){return{ok:!1,error:`Failed to restore checkpoint: ${nr(t)}`}}}function By(r){return r==="local"?`${S}LOCAL${f}`:r==="remote"?`${_}SERVER${f}`:`${ne}MANUAL${f}`}function Xl(r){let e=Date.now()-r.getTime(),t=Math.floor(e/6e4),n=Math.floor(t/60),i=Math.floor(n/24);return i>7?`${r.toLocaleDateString()} ${r.toLocaleTimeString()}`:i>0?`${i} day${i===1?"":"s"} ago`:n>0?`${n} hour${n===1?"":"s"} ago`:t>0?`${t} minute${t===1?"":"s"} ago`:"just now"}function Yy(r,e,t){if(r.length===0){console.log("No checkpoints found.");return}console.log(`
77
- ${J}Checkpoint History${f}
78
- `);let n=String(r.length).length;r.forEach((i,o)=>{let s=o+1,a=`${y}${String(s).padStart(n," ")}${f}`,l=i.isMajor?`${C}[MAJOR]${f}`:`${y}[minor]${f}`,u=i.isMilestone?`${C}\u2B50${f} ${ne}[${i.milestoneName}]${f} `:"";console.log(`${a} ${C}${i.shortHash}${f} ${u}${By(i.source)} ${l} ${i.message} ${y}(${i.filesChanged} files)${f}`),console.log(` ${y}${Xl(i.date)}${f}
79
- `)}),e&&console.log(`${y}Showing first ${t} checkpoints. Pass --limit <n> to see more.${f}`),console.log(`${y}Restore: boxel realm history <local-dir> -r <ref>${f}`)}function Xy(r){if(r===void 0)return Yl;if(!/^\d+$/.test(r))return null;let e=parseInt(r,10);return e>0?e:null}function Ce(r){console.error(`${h}Error:${f} ${r}`),process.exit(1)}function zl(r){r.command("history").alias("hist").description("View, restore, or create local checkpoints stored under .boxel-history/").argument("<local-dir>","The local workspace directory").option("-r, --restore <ref>","Restore the workspace to a checkpoint (1-based index, short hash, or full hash)").option("-m, --message <message>","Create a manual checkpoint with the given message").option("-y, --yes","Skip the interactive confirmation prompt before --restore").option("--limit <n>",`Maximum number of checkpoints to list or consider for --restore (default: ${Yl})`).action(async(e,t)=>{t.restore!==void 0&&t.message!==void 0&&Ce("Only one of --restore or --message may be specified.");let n=Xy(t.limit);if(n===null&&Ce("--limit must be a positive integer."),t.message!==void 0){let o=await Vy(e,t.message);o.ok||Ce(o.error),console.log(`${S}\u2713${f} Checkpoint created: ${C}${o.created.shortHash}${f} ${o.created.message}`);return}if(t.restore!==void 0){let o=await Hy(e,t.restore,n);o.ok||Ce(o.error);let s=o.target;if(!t.yes){process.stdin.isTTY||Ce("--restore overwrites local files. Pass --yes to confirm in non-interactive mode."),console.log(`
80
- ${J}Restoring to:${f} ${C}${s.shortHash}${f} - ${s.message}`),console.log(`${y}${Xl(s.date)}${f}
81
- `);let l=await K(`${C}This will overwrite current files. Continue? (y/N) ${f}`);if(!/^y/i.test(l)){console.log(`${y}Restore cancelled.${f}`);return}}let a=await Wy(e,s.hash);a.ok||Ce(a.error),console.log(`${S}\u2713${f} Restored to ${C}${s.shortHash}${f} ${s.message}`),console.log(`${y}Run 'boxel realm sync <local-dir> <realm-url> --prefer-local' to push the restored state to the realm.${f}`);return}let i=await Gy(e,n);i.ok||Ce(i.error),Yy(i.checkpoints,i.truncated,n)})}var zy="--all-accessible and --hidden are mutually exclusive";async function Jy(r={}){if(r.allAccessible&&r.hidden)return{realms:[],error:zy};let e=r.profileManager??A(),t=e.getActiveProfile();if(!t)return{realms:[],error:M};let n=t.profile.realmServerUrl.replace(/\/$/,""),i=await e.authedRealmServerFetch(`${n}/_realm-auth`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"}});if(!i.ok){let c=await i.text();return{realms:[],error:`Realm auth lookup failed: ${i.status} ${c}`}}let o=await i.json(),s=Object.keys(o).map(P),a;try{a=await e.getUserRealms()}catch(c){return{realms:[],error:`Failed to load UI realm list: ${c instanceof Error?c.message:String(c)}`}}let l=new Set(a.map(P)),u=s.map(c=>({url:c,hidden:!l.has(c)}));return r.allAccessible||(r.hidden?u=u.filter(c=>c.hidden):u=u.filter(c=>!c.hidden)),u.sort((c,m)=>c.url.localeCompare(m.url)),{realms:u}}function Jl(r){r.command("list").alias("ls").description("List realms accessible to the active profile").option("--json","Output JSON").option("--all-accessible","Show all accessible realms, including hidden ones").option("--hidden","Show only realms not in the user's UI realm list").action(async e=>{let t;try{t=await Jy({allAccessible:e.allAccessible,hidden:e.hidden})}catch(n){console.error(`${h}Error:${f} ${n instanceof Error?n.message:String(n)}`),process.exit(1)}if(e.json){console.log(JSON.stringify(t,null,2)),t.error&&process.exit(1);return}if(t.error&&(console.error(`${h}Error:${f} ${t.error}`),process.exit(1)),t.realms.length===0){console.log(`${y}No realms found.${f}`);return}console.log(`${J}${t.realms.length} realm(s):${f}`);for(let n of t.realms){let i=n.hidden?` ${y}(hidden)${f}`:"";console.log(` ${_}${n.url}${f}${i}`)}})}var or=O(require("fs"));var Wn=100;function sr(r){return r instanceof Error?r.message:String(r)}function Ky(r){let e=Date.now()-r.getTime(),t=Math.floor(e/6e4),n=Math.floor(t/60),i=Math.floor(n/24);return i>7?`${r.toLocaleDateString()} ${r.toLocaleTimeString()}`:i>0?`${i} day${i===1?"":"s"} ago`:n>0?`${n} hour${n===1?"":"s"} ago`:t>0?`${t} minute${t===1?"":"s"} ago`:"just now"}async function Kl(r,e,t){try{let n=new U(r);if(!await n.isInitialized())return{ok:!1,error:"No checkpoint history found for this workspace. Checkpoints are created automatically during sync operations."};let i=await n.getCheckpoints(t),o=rr(e,i);if(o.kind==="none")return{ok:!1,error:`Checkpoint not found: ${e}. Use a number (1-${i.length}) or a commit hash.`};if(o.kind==="ambiguous"){let s=o.matches.slice(0,5).map(l=>l.shortHash).join(", "),a=o.matches.length>5?", \u2026":"";return{ok:!1,error:`Ambiguous reference: ${e} matches ${o.matches.length} checkpoints (${s}${a}). Use a longer prefix or full hash.`}}return{ok:!0,target:o.target}}catch(n){return{ok:!1,error:`Failed to read checkpoints: ${sr(n)}`}}}async function Qy(r){if(!or.existsSync(r))return{ok:!1,error:`Directory not found: ${r}`};try{let e=new U(r);return await e.isInitialized()?{ok:!0,milestones:await e.getMilestones()}:{ok:!0,milestones:[]}}catch(e){return{ok:!1,error:`Failed to read milestones: ${sr(e)}`}}}async function Zy(r,e,t,n){if(!or.existsSync(r))return{ok:!1,error:`Directory not found: ${r}`};let i=t.trim();if(!i)return{ok:!1,error:"--name must not be empty."};let o=await Kl(r,e,n);if(!o.ok)return o;try{let s=new U(r);if(!await s.markMilestone(o.target.hash,i))return{ok:!1,error:"Could not mark milestone. The checkpoint may already have one."};let u=(await s.getCheckpoints(n)).find(c=>c.hash===o.target.hash);return u?{ok:!0,marked:u}:{ok:!1,error:"Milestone created but checkpoint could not be re-read."}}catch(s){return{ok:!1,error:`Failed to mark milestone: ${sr(s)}`}}}async function ew(r,e,t){if(!or.existsSync(r))return{ok:!1,error:`Directory not found: ${r}`};let n=await Kl(r,e,t);if(!n.ok)return n;let i=n.target;if(!i.isMilestone)return{ok:!1,error:`Checkpoint ${i.shortHash} is not marked as a milestone.`};try{return{ok:!0,removed:await new U(r).unmarkMilestone(i.hash)}}catch(o){return{ok:!1,error:`Failed to remove milestone: ${sr(o)}`}}}async function tw(r,e={}){if(e.mark!==void 0&&e.remove!==void 0)return{ok:!1,error:"Only one of --mark or --remove may be specified."};if(e.limit!==void 0&&(!Number.isInteger(e.limit)||e.limit<=0))return{ok:!1,error:"limit must be a positive integer."};let t=e.limit??Wn;if(e.mark!==void 0){if(e.name===void 0)return{ok:!1,error:"--name is required when using --mark."};let i=await Zy(r,e.mark,e.name,t);return i.ok?{ok:!0,marked:i.marked}:{ok:!1,error:i.error}}if(e.remove!==void 0){let i=await ew(r,e.remove,t);return i.ok?{ok:!0,removed:i.removed}:{ok:!1,error:i.error}}let n=await Qy(r);return n.ok?{ok:!0,milestones:n.milestones}:{ok:!1,error:n.error}}function rw(r,e){if(r.length===0){console.log(`
76
+ `).map(i=>this.parseCheckpointLine(i,e))):[]}git(...e){return new Promise((t,n)=>{let i=(0,Bl.spawn)("git",e,{cwd:this.gitDir}),o="",s="";i.stdout.on("data",a=>{o+=a.toString("utf-8")}),i.stderr.on("data",a=>{s+=a.toString("utf-8")}),i.on("error",a=>n(a)),i.on("close",a=>{if(a!==0&&!e.includes("status")){n(new Error(`git ${e.join(" ")} failed: ${s}`));return}t(o)})})}};function tr(r,e){let t=r.trim();if(t==="")return{kind:"none"};if(t.length===7){let i=e.filter(o=>o.shortHash===t);if(i.length===1)return{kind:"found",target:i[0]};if(i.length>1)return{kind:"ambiguous",matches:i}}if(/^\d+$/.test(t)){let i=parseInt(t,10);return i>=1&&i<=e.length?{kind:"found",target:e[i-1]}:{kind:"none"}}let n=e.filter(i=>i.hash.startsWith(t));return n.length===0?{kind:"none"}:n.length===1?{kind:"found",target:n[0]}:{kind:"ambiguous",matches:n}}var Yl=100;function rr(r){return r instanceof Error?r.message:String(r)}async function Gy(r,e){if(!st.existsSync(r))return{ok:!1,error:`Directory not found: ${r}`};try{let t=new U(r);if(!await t.isInitialized())return{ok:!0,checkpoints:[],truncated:!1};let n=await t.getCheckpoints(e+1),i=n.length>e;return{ok:!0,checkpoints:i?n.slice(0,e):n,truncated:i}}catch(t){return{ok:!1,error:`Failed to read checkpoint history: ${rr(t)}`}}}async function Vy(r,e){if(!st.existsSync(r))return{ok:!1,error:`Directory not found: ${r}`};let t=e.trim();if(!t)return{ok:!1,error:"--message must not be empty."};try{let n=new U(r);await n.isInitialized()||await n.init();let i=await n.detectCurrentChanges(),o=await n.createCheckpoint("manual",i,t);return o?{ok:!0,created:o}:{ok:!1,error:"No changes to checkpoint."}}catch(n){return{ok:!1,error:`Failed to create checkpoint: ${rr(n)}`}}}async function Hy(r,e,t){if(!st.existsSync(r))return{ok:!1,error:`Directory not found: ${r}`};try{let n=new U(r);if(!await n.isInitialized())return{ok:!1,error:"No checkpoint history found for this workspace. Checkpoints are created automatically during sync operations."};let i=await n.getCheckpoints(t),o=tr(e,i);if(o.kind==="none")return{ok:!1,error:`Checkpoint not found: ${e}. Use a number (1-${i.length}) or a commit hash.`};if(o.kind==="ambiguous"){let s=o.matches.slice(0,5).map(l=>l.shortHash).join(", "),a=o.matches.length>5?", \u2026":"";return{ok:!1,error:`Ambiguous reference: ${e} matches ${o.matches.length} checkpoints (${s}${a}). Use a longer prefix or full hash.`}}return{ok:!0,target:o.target}}catch(n){return{ok:!1,error:`Failed to read checkpoint history: ${rr(n)}`}}}async function Wy(r,e){if(!st.existsSync(r))return{ok:!1,error:`Directory not found: ${r}`};try{let t=new U(r);return await t.isInitialized()?(await t.restore(e),{ok:!0}):{ok:!1,error:"No checkpoint history found for this workspace."}}catch(t){return{ok:!1,error:`Failed to restore checkpoint: ${rr(t)}`}}}function By(r){return r==="local"?`${S}LOCAL${f}`:r==="remote"?`${_}SERVER${f}`:`${ie}MANUAL${f}`}function Xl(r){let e=Date.now()-r.getTime(),t=Math.floor(e/6e4),n=Math.floor(t/60),i=Math.floor(n/24);return i>7?`${r.toLocaleDateString()} ${r.toLocaleTimeString()}`:i>0?`${i} day${i===1?"":"s"} ago`:n>0?`${n} hour${n===1?"":"s"} ago`:t>0?`${t} minute${t===1?"":"s"} ago`:"just now"}function Yy(r,e,t){if(r.length===0){console.log("No checkpoints found.");return}console.log(`
77
+ ${K}Checkpoint History${f}
78
+ `);let n=String(r.length).length;r.forEach((i,o)=>{let s=o+1,a=`${g}${String(s).padStart(n," ")}${f}`,l=i.isMajor?`${C}[MAJOR]${f}`:`${g}[minor]${f}`,u=i.isMilestone?`${C}\u2B50${f} ${ie}[${i.milestoneName}]${f} `:"";console.log(`${a} ${C}${i.shortHash}${f} ${u}${By(i.source)} ${l} ${i.message} ${g}(${i.filesChanged} files)${f}`),console.log(` ${g}${Xl(i.date)}${f}
79
+ `)}),e&&console.log(`${g}Showing first ${t} checkpoints. Pass --limit <n> to see more.${f}`),console.log(`${g}Restore: boxel realm history <local-dir> -r <ref>${f}`)}function Xy(r){if(r===void 0)return Yl;if(!/^\d+$/.test(r))return null;let e=parseInt(r,10);return e>0?e:null}function Ae(r){console.error(`${h}Error:${f} ${r}`),process.exit(1)}function zl(r){r.command("history").alias("hist").description("View, restore, or create local checkpoints stored under .boxel-history/").argument("<local-dir>","The local workspace directory").option("-r, --restore <ref>","Restore the workspace to a checkpoint (1-based index, short hash, or full hash)").option("-m, --message <message>","Create a manual checkpoint with the given message").option("-y, --yes","Skip the interactive confirmation prompt before --restore").option("--limit <n>",`Maximum number of checkpoints to list or consider for --restore (default: ${Yl})`).action(async(e,t)=>{t.restore!==void 0&&t.message!==void 0&&Ae("Only one of --restore or --message may be specified.");let n=Xy(t.limit);if(n===null&&Ae("--limit must be a positive integer."),t.message!==void 0){let o=await Vy(e,t.message);o.ok||Ae(o.error),console.log(`${S}\u2713${f} Checkpoint created: ${C}${o.created.shortHash}${f} ${o.created.message}`);return}if(t.restore!==void 0){let o=await Hy(e,t.restore,n);o.ok||Ae(o.error);let s=o.target;if(!t.yes){process.stdin.isTTY||Ae("--restore overwrites local files. Pass --yes to confirm in non-interactive mode."),console.log(`
80
+ ${K}Restoring to:${f} ${C}${s.shortHash}${f} - ${s.message}`),console.log(`${g}${Xl(s.date)}${f}
81
+ `);let l=await Q(`${C}This will overwrite current files. Continue? (y/N) ${f}`);if(!/^y/i.test(l)){console.log(`${g}Restore cancelled.${f}`);return}}let a=await Wy(e,s.hash);a.ok||Ae(a.error),console.log(`${S}\u2713${f} Restored to ${C}${s.shortHash}${f} ${s.message}`),console.log(`${g}Run 'boxel realm sync <local-dir> <realm-url> --prefer-local' to push the restored state to the realm.${f}`);return}let i=await Gy(e,n);i.ok||Ae(i.error),Yy(i.checkpoints,i.truncated,n)})}var zy="--all-accessible and --hidden are mutually exclusive";async function Jy(r={}){if(r.allAccessible&&r.hidden)return{realms:[],error:zy};let e=r.profileManager??A(),t=e.getActiveProfile();if(!t)return{realms:[],error:M};let n=t.profile.realmServerUrl.replace(/\/$/,""),i=await e.authedRealmServerFetch(`${n}/_realm-auth`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"}});if(!i.ok){let c=await i.text();return{realms:[],error:`Realm auth lookup failed: ${i.status} ${c}`}}let o=await i.json(),s=Object.keys(o).map(P),a;try{a=await e.getUserRealms()}catch(c){return{realms:[],error:`Failed to load UI realm list: ${c instanceof Error?c.message:String(c)}`}}let l=new Set(a.map(P)),u=s.map(c=>({url:c,hidden:!l.has(c)}));return r.allAccessible||(r.hidden?u=u.filter(c=>c.hidden):u=u.filter(c=>!c.hidden)),u.sort((c,m)=>c.url.localeCompare(m.url)),{realms:u}}function Jl(r){r.command("list").alias("ls").description("List realms accessible to the active profile").option("--json","Output JSON").option("--all-accessible","Show all accessible realms, including hidden ones").option("--hidden","Show only realms not in the user's UI realm list").action(async e=>{let t;try{t=await Jy({allAccessible:e.allAccessible,hidden:e.hidden})}catch(n){console.error(`${h}Error:${f} ${n instanceof Error?n.message:String(n)}`),process.exit(1)}if(e.json){console.log(JSON.stringify(t,null,2)),t.error&&process.exit(1);return}if(t.error&&(console.error(`${h}Error:${f} ${t.error}`),process.exit(1)),t.realms.length===0){console.log(`${g}No realms found.${f}`);return}console.log(`${K}${t.realms.length} realm(s):${f}`);for(let n of t.realms){let i=n.hidden?` ${g}(hidden)${f}`:"";console.log(` ${_}${n.url}${f}${i}`)}})}var ir=O(require("fs"));var Bn=100;function or(r){return r instanceof Error?r.message:String(r)}function Ky(r){let e=Date.now()-r.getTime(),t=Math.floor(e/6e4),n=Math.floor(t/60),i=Math.floor(n/24);return i>7?`${r.toLocaleDateString()} ${r.toLocaleTimeString()}`:i>0?`${i} day${i===1?"":"s"} ago`:n>0?`${n} hour${n===1?"":"s"} ago`:t>0?`${t} minute${t===1?"":"s"} ago`:"just now"}async function Kl(r,e,t){try{let n=new U(r);if(!await n.isInitialized())return{ok:!1,error:"No checkpoint history found for this workspace. Checkpoints are created automatically during sync operations."};let i=await n.getCheckpoints(t),o=tr(e,i);if(o.kind==="none")return{ok:!1,error:`Checkpoint not found: ${e}. Use a number (1-${i.length}) or a commit hash.`};if(o.kind==="ambiguous"){let s=o.matches.slice(0,5).map(l=>l.shortHash).join(", "),a=o.matches.length>5?", \u2026":"";return{ok:!1,error:`Ambiguous reference: ${e} matches ${o.matches.length} checkpoints (${s}${a}). Use a longer prefix or full hash.`}}return{ok:!0,target:o.target}}catch(n){return{ok:!1,error:`Failed to read checkpoints: ${or(n)}`}}}async function Qy(r){if(!ir.existsSync(r))return{ok:!1,error:`Directory not found: ${r}`};try{let e=new U(r);return await e.isInitialized()?{ok:!0,milestones:await e.getMilestones()}:{ok:!0,milestones:[]}}catch(e){return{ok:!1,error:`Failed to read milestones: ${or(e)}`}}}async function Zy(r,e,t,n){if(!ir.existsSync(r))return{ok:!1,error:`Directory not found: ${r}`};let i=t.trim();if(!i)return{ok:!1,error:"--name must not be empty."};let o=await Kl(r,e,n);if(!o.ok)return o;try{let s=new U(r);if(!await s.markMilestone(o.target.hash,i))return{ok:!1,error:"Could not mark milestone. The checkpoint may already have one."};let u=(await s.getCheckpoints(n)).find(c=>c.hash===o.target.hash);return u?{ok:!0,marked:u}:{ok:!1,error:"Milestone created but checkpoint could not be re-read."}}catch(s){return{ok:!1,error:`Failed to mark milestone: ${or(s)}`}}}async function ew(r,e,t){if(!ir.existsSync(r))return{ok:!1,error:`Directory not found: ${r}`};let n=await Kl(r,e,t);if(!n.ok)return n;let i=n.target;if(!i.isMilestone)return{ok:!1,error:`Checkpoint ${i.shortHash} is not marked as a milestone.`};try{return{ok:!0,removed:await new U(r).unmarkMilestone(i.hash)}}catch(o){return{ok:!1,error:`Failed to remove milestone: ${or(o)}`}}}async function tw(r,e={}){if(e.mark!==void 0&&e.remove!==void 0)return{ok:!1,error:"Only one of --mark or --remove may be specified."};if(e.limit!==void 0&&(!Number.isInteger(e.limit)||e.limit<=0))return{ok:!1,error:"limit must be a positive integer."};let t=e.limit??Bn;if(e.mark!==void 0){if(e.name===void 0)return{ok:!1,error:"--name is required when using --mark."};let i=await Zy(r,e.mark,e.name,t);return i.ok?{ok:!0,marked:i.marked}:{ok:!1,error:i.error}}if(e.remove!==void 0){let i=await ew(r,e.remove,t);return i.ok?{ok:!0,removed:i.removed}:{ok:!1,error:i.error}}let n=await Qy(r);return n.ok?{ok:!0,milestones:n.milestones}:{ok:!1,error:n.error}}function rw(r,e){if(r.length===0){console.log(`
82
82
  No milestones marked yet.
83
83
  `),console.log(`Use ${_}boxel realm milestone <local-dir> --mark <ref> --name <name>${f} to mark a checkpoint.`),console.log(`Use ${_}boxel realm history <local-dir>${f} to see available checkpoints.
84
84
  `);return}console.log(`
85
- ${J}Milestones${f} ${y}(${e})${f}
86
- `);for(let t of r){let n=t.source==="local"?"\u2191":t.source==="remote"?"\u2193":"\u25CF",i=t.source==="local"?S:t.source==="remote"?_:ne;console.log(` ${C}\u2B50${f} ${C}${t.shortHash}${f} ${i}${n}${f} ${ne}[${t.milestoneName}]${f} ${t.message}`),console.log(` ${y}${Ky(t.date)}${f}`)}console.log()}function nw(r){if(r===void 0)return Wn;if(!/^\d+$/.test(r))return null;let e=parseInt(r,10);return e>0?e:null}function ir(r){console.error(`${h}Error:${f} ${r}`),process.exit(1)}function Ql(r){r.command("milestone").description("List, mark, or remove milestones in the local .boxel-history/ checkpoint log").argument("<local-dir>","The local workspace directory").option("--mark <ref>","Mark a checkpoint as a milestone (1-based index, short hash, or full hash)").option("--name <name>","Name for the milestone (required with --mark)").option("--remove <ref>","Remove the milestone tag from a checkpoint (1-based index, short hash, or full hash)").option("--limit <n>",`Maximum number of checkpoints to consider for ref resolution (default: ${Wn})`).option("--json","Output result as JSON").action(async(e,t)=>{t.mark!==void 0&&t.remove!==void 0&&ir("Only one of --mark or --remove may be specified.");let n=nw(t.limit);n===null&&ir("--limit must be a positive integer."),t.mark!==void 0&&t.name===void 0&&ir("--name is required when using --mark.");let i=await tw(e,{mark:t.mark,name:t.name,remove:t.remove,limit:n});if(t.json){N.output(JSON.stringify(i,null,2)),i.ok||process.exit(1);return}if(i.ok||ir(i.error),i.marked){let o=i.marked;console.log(`
87
- ${S}\u2713${f} ${C}\u2B50${f} Milestone created: ${ne}${o.milestoneName}${f}`),console.log(` Checkpoint: ${C}${o.shortHash}${f} ${o.message}`),console.log();return}if(i.removed!==void 0){console.log(`${S}\u2713${f} Milestone removed`);return}rw(i.milestones,e)})}var Zl=O(bn()),ec="realm_server";function iw(r){let{hostname:e}=new URL(r);if(e==="localhost"||e.endsWith(".localhost"))return"localhost";let t=e.split(".");return t.length<=2?e:t.slice(-2).join(".")}function ow(r,e=ec){return`@${e}:${iw(r)}`}function sw(r){return new URL(r).origin+"/"}function aw(r){try{return new URL(r).href.replace(/\/+$/,"")+"/"}catch{throw new Error(`Invalid realm URL: ${r}`)}}var ar=class{#e;#t;#r;#i;#n=new Map;constructor(e){if(!e.seed)throw new Error("SeedAuthenticator requires a non-empty seed");this.#e=e.seed,this.#t=e.botUsername??ec,this.#r=e.botUserId,this.#i=e.expiresIn??"7d"}buildClaims(e){let t=aw(e);return{user:this.#r??ow(t,this.#t),realm:t,sessionRoom:void 0,permissions:[],realmServerURL:sw(t)}}mintTokenForRealm(e){let t=this.buildClaims(e),n=this.#n.get(t.realm);if(n)return n;let i=Zl.default.sign(t,this.#e,{expiresIn:this.#i});return this.#n.set(t.realm,i),i}#o(e){for(let o of this.#n.keys())if(e.startsWith(o))return o;let t=new URL(e),n=t.pathname.split("/").filter(Boolean),i=n.length>0?`/${n.slice(0,2).join("/")}/`:"/";return`${t.origin}${i}`}async authedRealmFetch(e,t){let n=e instanceof Request?e.url:e instanceof URL?e.href:e,i=this.#o(n),o=this.mintTokenForRealm(i),s=this.#s(e,t,o);return fetch(e,{...t,headers:s})}#s(e,t,n){let i=e instanceof Request?new Headers(e.headers):new Headers,o=new Headers(t?.headers);for(let[s,a]of o)i.set(s,a);return i.has("Authorization")||i.set("Authorization",n),i}registerRealmUrl(e){this.mintTokenForRealm(e)}};function de(r){if(r.realmSecretSeed)try{let t=new ar({seed:r.realmSecretSeed});return t.registerRealmUrl(r.realmUrl),{ok:!0,authenticator:t,mode:"seed"}}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t)}}let e=r.profileManager??A();return e.getActiveProfile()?{ok:!0,authenticator:e,mode:"profile"}:{ok:!1,error:M}}var lr=O(require("fs/promises")),tc=O(require("path")),Bn=class extends ie{constructor(t,n){super(t,n);this.pullOptions=t}hasError=!1;downloadedFiles=[];async sync(){console.log(`Starting pull from ${this.options.realmUrl} to ${this.options.localDir}`),console.log("Testing realm access...");try{await this.getRemoteFileList("")}catch(l){throw console.error("Failed to access realm:",l),new Error("Cannot proceed with pull: Authentication or access failed. Please check your credentials and realm permissions.")}console.log("Realm access verified");let[t,n]=await Promise.all([this.getRemoteFileList(),this.getLocalFileList()]);if(console.log(`Found ${t.size} files in remote realm`),console.log(`Found ${n.size} files in local directory`),this.options.dryRun)try{await lr.access(this.options.localDir)}catch{console.log(`[DRY RUN] Would create directory: ${this.options.localDir}`)}else await lr.mkdir(this.options.localDir,{recursive:!0});let i=new Set;if(this.pullOptions.deleteLocal)for(let l of n.keys())t.has(l)||i.add(l);let o=new U(this.options.localDir);if(i.size>0&&!this.options.dryRun){let l=Array.from(i).map(c=>({file:c,status:"deleted"})),u=await o.createCheckpoint("remote",l,`Pre-delete checkpoint: ${i.size} files not on server`);u&&console.log(`
85
+ ${K}Milestones${f} ${g}(${e})${f}
86
+ `);for(let t of r){let n=t.source==="local"?"\u2191":t.source==="remote"?"\u2193":"\u25CF",i=t.source==="local"?S:t.source==="remote"?_:ie;console.log(` ${C}\u2B50${f} ${C}${t.shortHash}${f} ${i}${n}${f} ${ie}[${t.milestoneName}]${f} ${t.message}`),console.log(` ${g}${Ky(t.date)}${f}`)}console.log()}function nw(r){if(r===void 0)return Bn;if(!/^\d+$/.test(r))return null;let e=parseInt(r,10);return e>0?e:null}function nr(r){console.error(`${h}Error:${f} ${r}`),process.exit(1)}function Ql(r){r.command("milestone").description("List, mark, or remove milestones in the local .boxel-history/ checkpoint log").argument("<local-dir>","The local workspace directory").option("--mark <ref>","Mark a checkpoint as a milestone (1-based index, short hash, or full hash)").option("--name <name>","Name for the milestone (required with --mark)").option("--remove <ref>","Remove the milestone tag from a checkpoint (1-based index, short hash, or full hash)").option("--limit <n>",`Maximum number of checkpoints to consider for ref resolution (default: ${Bn})`).option("--json","Output result as JSON").action(async(e,t)=>{t.mark!==void 0&&t.remove!==void 0&&nr("Only one of --mark or --remove may be specified.");let n=nw(t.limit);n===null&&nr("--limit must be a positive integer."),t.mark!==void 0&&t.name===void 0&&nr("--name is required when using --mark.");let i=await tw(e,{mark:t.mark,name:t.name,remove:t.remove,limit:n});if(t.json){N.output(JSON.stringify(i,null,2)),i.ok||process.exit(1);return}if(i.ok||nr(i.error),i.marked){let o=i.marked;console.log(`
87
+ ${S}\u2713${f} ${C}\u2B50${f} Milestone created: ${ie}${o.milestoneName}${f}`),console.log(` Checkpoint: ${C}${o.shortHash}${f} ${o.message}`),console.log();return}if(i.removed!==void 0){console.log(`${S}\u2713${f} Milestone removed`);return}rw(i.milestones,e)})}var Zl=O(Rn()),ec="realm_server";function iw(r){let{hostname:e}=new URL(r);if(e==="localhost"||e.endsWith(".localhost"))return"localhost";let t=e.split(".");return t.length<=2?e:t.slice(-2).join(".")}function ow(r,e=ec){return`@${e}:${iw(r)}`}function sw(r){return new URL(r).origin+"/"}function aw(r){try{return new URL(r).href.replace(/\/+$/,"")+"/"}catch{throw new Error(`Invalid realm URL: ${r}`)}}var sr=class{#e;#t;#r;#i;#n=new Map;constructor(e){if(!e.seed)throw new Error("SeedAuthenticator requires a non-empty seed");this.#e=e.seed,this.#t=e.botUsername??ec,this.#r=e.botUserId,this.#i=e.expiresIn??"7d"}buildClaims(e){let t=aw(e);return{user:this.#r??ow(t,this.#t),realm:t,sessionRoom:void 0,permissions:[],realmServerURL:sw(t)}}mintTokenForRealm(e){let t=this.buildClaims(e),n=this.#n.get(t.realm);if(n)return n;let i=Zl.default.sign(t,this.#e,{expiresIn:this.#i});return this.#n.set(t.realm,i),i}#o(e){for(let o of this.#n.keys())if(e.startsWith(o))return o;let t=new URL(e),n=t.pathname.split("/").filter(Boolean),i=n.length>0?`/${n.slice(0,2).join("/")}/`:"/";return`${t.origin}${i}`}async authedRealmFetch(e,t){let n=e instanceof Request?e.url:e instanceof URL?e.href:e,i=this.#o(n),o=this.mintTokenForRealm(i),s=this.#s(e,t,o);return fetch(e,{...t,headers:s})}#s(e,t,n){let i=e instanceof Request?new Headers(e.headers):new Headers,o=new Headers(t?.headers);for(let[s,a]of o)i.set(s,a);return i.has("Authorization")||i.set("Authorization",n),i}registerRealmUrl(e){this.mintTokenForRealm(e)}};function de(r){if(r.realmSecretSeed)try{let t=new sr({seed:r.realmSecretSeed});return t.registerRealmUrl(r.realmUrl),{ok:!0,authenticator:t,mode:"seed"}}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t)}}let e=r.profileManager??A();return e.getActiveProfile()?{ok:!0,authenticator:e,mode:"profile"}:{ok:!1,error:M}}var ar=O(require("fs/promises")),tc=O(require("path")),Yn=class extends oe{constructor(t,n){super(t,n);this.pullOptions=t}hasError=!1;downloadedFiles=[];async sync(){console.log(`Starting pull from ${this.options.realmUrl} to ${this.options.localDir}`),console.log("Testing realm access...");try{await this.getRemoteFileList("")}catch(l){throw console.error("Failed to access realm:",l),new Error("Cannot proceed with pull: Authentication or access failed. Please check your credentials and realm permissions.")}console.log("Realm access verified");let[t,n]=await Promise.all([this.getRemoteFileList(),this.getLocalFileList()]);if(console.log(`Found ${t.size} files in remote realm`),console.log(`Found ${n.size} files in local directory`),this.options.dryRun)try{await ar.access(this.options.localDir)}catch{console.log(`[DRY RUN] Would create directory: ${this.options.localDir}`)}else await ar.mkdir(this.options.localDir,{recursive:!0});let i=new Set;if(this.pullOptions.deleteLocal)for(let l of n.keys())t.has(l)||i.add(l);let o=new U(this.options.localDir);if(i.size>0&&!this.options.dryRun){let l=Array.from(i).map(c=>({file:c,status:"deleted"})),u=await o.createCheckpoint("remote",l,`Pre-delete checkpoint: ${i.size} files not on server`);u&&console.log(`
88
88
  Checkpoint created before deletion: ${u.shortHash}`)}let s=await Promise.all(Array.from(t.keys()).map(l=>this.remoteLimit(async()=>{try{let u=tc.join(this.options.localDir,l);return await this.downloadFile(l,u),l}catch(u){return this.hasError=!0,console.error(`Error downloading ${l}:`,u),null}})));this.downloadedFiles=s.filter(l=>l!==null);let a=[];if(i.size>0&&(console.log(`
89
89
  Deleting ${i.size} local files that don't exist in realm...`),a=(await Promise.all(Array.from(i).map(async u=>{try{let c=n.get(u);return c?(await this.deleteLocalFile(c),console.log(` Deleted: ${u}`),u):null}catch(c){return this.hasError=!0,console.error(`Error deleting local file ${u}:`,c),null}}))).filter(u=>u!==null)),!this.options.dryRun&&this.downloadedFiles.length+a.length>0){let l=[...this.downloadedFiles.map(c=>({file:c,status:"modified"})),...a.map(c=>({file:c,status:"deleted"}))],u=await o.createCheckpoint("remote",l);if(u){let c=u.isMajor?"[MAJOR]":"[minor]";console.log(`
90
- Checkpoint created: ${u.shortHash} ${c} ${u.message}`)}}console.log("Pull completed")}};function rc(r){r.command("pull").description("Pull files from a Boxel realm to a local directory").argument("<realm-url>","The URL of the source realm (e.g., https://app.boxel.ai/demo/)").argument("<local-dir>","The local directory to sync files to").option("--delete","Delete local files that do not exist in the realm").option("--dry-run","Show what would be done without making changes").option("--realm-secret-seed","Administrative auth: prompt for a realm secret seed and mint a JWT locally instead of using a Matrix profile (env: BOXEL_REALM_SECRET_SEED)").action(async(e,t,n)=>{let i=await me(n.realmSecretSeed===!0),o=await lw(e,t,{delete:n.delete,dryRun:n.dryRun,realmSecretSeed:i});o.error&&(console.error(`Error: ${o.error}`),process.exit(o.files.length>0?2:1)),console.log("Pull completed successfully")})}async function lw(r,e,t){let n;if(t.authenticator)n=t.authenticator;else{let i=de({realmUrl:r,realmSecretSeed:t.realmSecretSeed,profileManager:t.profileManager});if(!i.ok)return{files:[],error:i.error};n=i.authenticator}try{let i=new Bn({realmUrl:r,localDir:e,deleteLocal:t.delete,dryRun:t.dryRun},n);return await i.sync(),i.hasError?{files:i.downloadedFiles.sort(),error:"Pull completed with errors. Some files may not have been downloaded."}:{files:i.downloadedFiles.sort()}}catch(i){return{files:[],error:`Pull failed: ${i instanceof Error?i.message:String(i)}`}}}var Ae=O(require("fs/promises")),Yn=O(require("path")),nc=O(require("crypto"));function Xn(r){if(typeof r!="object"||r===null)return!1;let e=r;if(typeof e.realmUrl!="string"||typeof e.files!="object"||e.files===null)return!1;for(let t of Object.values(e.files))if(typeof t!="string")return!1;if(e.remoteMtimes!==void 0){if(typeof e.remoteMtimes!="object"||e.remoteMtimes===null)return!1;for(let t of Object.values(e.remoteMtimes))if(typeof t!="number")return!1}return!0}async function Ge(r){try{return await Ae.access(r),!0}catch{return!1}}async function oe(r){let e=await Ae.readFile(r);return nc.createHash("md5").update(e).digest("hex")}async function ye(r){let e=Yn.join(r,".boxel-sync.json"),t;try{t=await Ae.readFile(e,"utf8")}catch(i){if(i.code==="ENOENT")return null;throw i}let n;try{n=JSON.parse(t)}catch{return null}return Xn(n)?n:(console.warn("Warning: .boxel-sync.json is malformed or has an unexpected shape; falling back to a full upload."),null)}async function Re(r,e){let t=Yn.join(r,".boxel-sync.json");await Ae.writeFile(t,JSON.stringify(e,null,2))}var cw=new Set(["index.json","realm.json"]),zn=class extends ie{constructor(t,n){super(t,n);this.pushOptions=t}hasError=!1;async sync(){console.log(`Starting push from ${this.options.localDir} to ${this.options.realmUrl}`),console.log("Testing realm access...");let t;try{t=await this.getRemoteFileList("")}catch(c){throw console.error("Failed to access realm:",c),new Error("Cannot proceed with push: Authentication or access failed. Please check your credentials and realm permissions.")}console.log("Realm access verified");let n=await this.getLocalFileList();console.log(`Found ${n.size} files in local directory`);let i=await ye(this.options.localDir),o={realmUrl:this.normalizedRealmUrl,files:{},remoteMtimes:{}},s=new Map,a=new Set;if(!this.pushOptions.force&&i!==null&&i.realmUrl===this.normalizedRealmUrl){console.log("Checking for changed files...");let c=0,[m,d]=await Promise.all([this.getRemoteMtimes(),Promise.all(Array.from(n.entries()).map(async([p,w])=>{if(D(p))return{relativePath:p,localPath:w,currentHash:"",protected:!0};let x=await oe(w);return{relativePath:p,localPath:w,currentHash:x,protected:!1}}))]);for(let p of d){if(p.protected){c++;continue}let w=i.files[p.relativePath],x=i.remoteMtimes?.[p.relativePath],Q=m.get(p.relativePath),ft=w!==p.currentHash,b=w!==void 0&&!t.has(p.relativePath),R=x!==void 0&&Q!==void 0&&Q!==x;ft||b||R?(s.set(p.relativePath,p.localPath),!ft&&(b||R)&&a.add(p.relativePath)):(c++,o.files[p.relativePath]=p.currentHash,x!==void 0&&(o.remoteMtimes[p.relativePath]=x))}if(c>0&&console.log(`Skipping ${c} unchanged files`),a.size>0){let p=Array.from(a),w=p.slice(0,5).join(", "),x=p.length>5?", ...":"";console.warn(`Warning: ${a.size} file(s) changed on the realm since your last push; your local versions will overwrite them: ${w}${x}`)}}else{this.pushOptions.force?console.log("Force mode: uploading all files"):console.log(i?"Realm URL changed, will upload all files":"No sync manifest found, will upload all files");for(let[c,m]of n)D(c)||s.set(c,m)}let u=!1;if(s.size===0)console.log("No files to upload - everything is up to date");else{console.log(`Uploading ${s.size} file(s) via /_atomic...`);let c=new Set,m=this.pushOptions.force||!i;for(let p of s.keys())if(m)t.has(p)||c.add(p);else{let w=i.files[p]!==void 0,x=w&&!t.has(p);(!w||x)&&c.add(p)}let d=await this.uploadFilesAtomic(s,c);if(d.error){u=!0,this.hasError=!0,console.error(d.error.message);for(let p of d.error.perFile){let w;p.status===409?w=`${p.path} was created on the realm concurrently \u2014 run with --force to overwrite.`:p.status===404?w=`${p.path} was removed from the realm concurrently \u2014 run with --force to re-create it from your local copy.`:w=`${p.path}: ${p.title}`,console.error(` ${w}`)}}else if(d.succeeded.length>0){let p=await Promise.all(d.succeeded.map(async w=>({rel:w,hash:await oe(s.get(w))})));for(let{rel:w,hash:x}of p)o.files[w]=x}}if(this.pushOptions.deleteRemote){let c=new Set(t.keys()),m=[];for(let d of c){if(D(d)){c.delete(d);continue}cw.has(d)&&(c.delete(d),m.push(d))}for(let d of n.keys())c.delete(d);if(m.length>0&&console.log(`Skipping ${m.length} realm-managed remote artifact(s): ${m.join(", ")}`),c.size>0){let d=Array.from(c).sort();console.log(`Deleting ${d.length} remote files that don't exist locally: ${d.join(", ")}`);for(let p of d)try{await this.deleteFile(p)}catch(w){this.hasError=!0,console.error(`Error deleting ${p}:`,w)}}}if(!this.options.dryRun&&!u&&s.size>0)try{let c=await this.getRemoteMtimes();for(let m of Object.keys(o.files)){let d=c.get(m);d!==void 0&&(o.remoteMtimes[m]=d)}}catch(c){console.warn("Could not refresh remote mtimes after upload:",c)}if(o.remoteMtimes&&Object.keys(o.remoteMtimes).length===0&&delete o.remoteMtimes,!this.options.dryRun&&!u&&await Re(this.options.localDir,o),!this.options.dryRun&&s.size>0&&!u){let c=new U(this.options.localDir),m=Array.from(s.keys()).map(p=>({file:p,status:"modified"})),d=await c.createCheckpoint("local",m);if(d){let p=d.isMajor?"[MAJOR]":"[minor]";console.log(`
91
- Checkpoint created: ${d.shortHash} ${p} ${d.message}`)}}console.log("Push completed")}};function ic(r){r.command("push").description("Push local files to a Boxel realm").argument("<local-dir>","The local directory containing files to sync").argument("<realm-url>","The URL of the target realm (e.g., https://app.boxel.ai/demo/)").option("--delete","Delete remote files that do not exist locally").option("--dry-run","Show what would be done without making changes").option("--force","Upload all files, even if unchanged").option("--realm-secret-seed","Administrative auth: prompt for a realm secret seed and mint a JWT locally instead of using a Matrix profile (env: BOXEL_REALM_SECRET_SEED)").action(async(e,t,n)=>{let i=await me(n.realmSecretSeed===!0);await uw(e,t,{delete:n.delete,dryRun:n.dryRun,force:n.force,realmSecretSeed:i})})}async function uw(r,e,t){let n;if(t.authenticator)n=t.authenticator;else{let i=de({realmUrl:e,realmSecretSeed:t.realmSecretSeed,profileManager:t.profileManager});i.ok||(console.error(`Error: ${i.error}`),process.exit(1)),n=i.authenticator}await Ge(r)||(console.error(`Local directory does not exist: ${r}`),process.exit(1));try{let i=new zn({realmUrl:e,localDir:r,deleteRemote:t.delete,dryRun:t.dryRun,force:t.force},n);await i.sync(),i.hasError?(console.log("Push did not complete successfully. View logs for details"),process.exit(2)):console.log("Push completed successfully")}catch(i){console.error("Push failed:",i),process.exit(1)}}async function oc(r){let e=P(r.realmUrl.trim()),t=r.profileManager??A(),n=t.getActiveProfile();if(!n)return{realmUrl:e,removed:!1,serverDeleted:!1,unlinked:!1,previousCount:0,nextCount:0,error:M};let i;try{i=await t.getUserRealms()}catch(d){return{realmUrl:e,removed:!1,serverDeleted:!1,unlinked:!1,previousCount:0,nextCount:0,error:`Failed to load realm list: ${d instanceof Error?d.message:String(d)}`}}let o=i.map(P),s=o.length,a=o.filter(d=>d===e).length;if(a===0)return{realmUrl:e,removed:!1,serverDeleted:!1,unlinked:!1,previousCount:s,nextCount:s,notInList:!0,error:"Realm is not in app.boxel.realms. Nothing to remove."};let l=s-a;if(r.dryRun)return{realmUrl:e,removed:!1,serverDeleted:!1,unlinked:!1,previousCount:s,nextCount:l};let u=n.profile.realmServerUrl.replace(/\/$/,""),c;try{c=await t.authedRealmServerFetch(`${u}/_delete-realm`,{method:"DELETE",headers:{"Content-Type":"application/vnd.api+json"},body:JSON.stringify({data:{type:"realm",id:e}})})}catch(d){return{realmUrl:e,removed:!1,serverDeleted:!1,unlinked:!1,previousCount:s,nextCount:s,error:`Failed to reach realm server: ${d instanceof Error?d.message:String(d)}`}}if(!c.ok){let d=await fw(c),p=c.status===403?`You do not own this realm and cannot delete it on the server. Server returned 403: ${d}`:`Realm server returned ${c.status}: ${d}`;return{realmUrl:e,removed:!1,serverDeleted:!1,unlinked:!1,previousCount:s,nextCount:s,error:p}}let m;try{m=await t.removeFromUserRealms(e)}catch(d){return{realmUrl:e,removed:!1,serverDeleted:!0,unlinked:!1,previousCount:s,nextCount:s,error:`Server delete succeeded, but Matrix unlink failed: ${d instanceof Error?d.message:String(d)}`}}return m?{realmUrl:e,removed:!0,serverDeleted:!0,unlinked:m,previousCount:s,nextCount:l}:{realmUrl:e,removed:!1,serverDeleted:!0,unlinked:!1,previousCount:s,nextCount:s,error:"Server delete succeeded, but Matrix account_data did not contain the URL by the time we PUT (concurrent edit?). Server-side files are gone; please refresh and check your realm list."}}async function fw(r){try{return await r.text()}catch{return"<no response body>"}}function sc(r){r.command("remove").description("Remove a realm \u2014 deletes server-side files and unlinks it from your realm list").argument("<realm-url>","realm URL to remove").option("-y, --yes","Skip the interactive confirmation prompt").option("--dry-run","Preview the change without writing to Matrix").action(async(e,t)=>{let n=P(e.trim()),i=await oc({realmUrl:n,dryRun:!0});if(i.error&&!i.notInList&&(console.error(`${h}Error:${f} ${i.error}`),process.exit(1)),i.notInList&&(console.error(`${h}Error:${f} ${i.error}`),process.exit(1)),console.log(`Remove target: ${_}${i.realmUrl}${f}`),console.log(`${y}app.boxel.realms: ${i.previousCount} -> ${i.nextCount}${f}`),t.dryRun){console.log(`${y}[DRY RUN] No server delete or Matrix changes sent.${f}`);return}if(!t.yes){process.stdin.isTTY||(console.error(`${h}Error:${f} stdin is not a TTY. Pass --yes to confirm in non-interactive mode.`),process.exit(1));let s=await K("This will permanently delete the realm files, indexer state, and registry entry on the server. Proceed? (y/N) ");if(!/^y/i.test(s)){console.log(`${y}Cancelled.${f}`);return}}let o=await oc({realmUrl:n});(o.error||!o.removed)&&(console.error(`${h}Error:${f} ${o.error??"Removal did not complete."}`),o.serverDeleted&&!o.unlinked&&console.error(`${y}The realm is gone, but your account_data still references ${o.realmUrl}.${f}`),process.exit(1)),console.log(`${S}Removed:${f} ${_}${o.realmUrl}${f}`)})}var Ve=O(require("fs/promises")),st=O(require("path"));function cr(r,e,t){let n=e.has(r),i=t?.files[r]!==void 0;return n&&i?e.get(r)===t.files[r]?"unchanged":"changed":n&&!i?"added":!n&&i?"deleted":"unchanged"}function ur(r,e,t){let n=e.has(r),i=t?.remoteMtimes?.[r]!==void 0,o=t?.files[r]!==void 0,s=i||o;return n&&i?e.get(r)===t.remoteMtimes[r]?"unchanged":"changed":n&&o?"changed":n&&!s?"added":!n&&s?"deleted":"unchanged"}function ac(r,e,t){return r==="unchanged"&&e==="unchanged"?"noop":r==="changed"&&e==="unchanged"?"push":r==="unchanged"&&e==="changed"?"pull":r==="added"&&e==="unchanged"?"push":r==="unchanged"&&e==="added"?"pull":r==="changed"&&e==="changed"||r==="added"&&e==="added"||r==="changed"&&e==="added"||r==="added"&&e==="changed"?"conflict":r==="deleted"&&e==="unchanged"?t.deleteSync||t.preferLocal?"push-delete":"noop":r==="unchanged"&&e==="deleted"?t.deleteSync||t.preferRemote?"pull-delete":"noop":r==="deleted"&&e==="changed"||r==="changed"&&e==="deleted"?"conflict":r==="deleted"&&e==="deleted"?"noop":r==="added"&&e==="deleted"?"push":r==="deleted"&&e==="added"?"pull":"noop"}function lc(r,e,t,n){let{localStatus:i,remoteStatus:o,relativePath:s}=r;if(!n)return null;switch(n){case"prefer-local":return i==="deleted"?"push-delete":"push";case"prefer-remote":return o==="deleted"?"pull-delete":"pull";case"prefer-newest":{if(i==="deleted"&&o==="changed")return"pull";if(i==="changed"&&o==="deleted")return"push";let a=e.get(s),l=t.get(s);return a&&l!==void 0?a.mtime>l*1e3?"push":"pull":"push"}}}var mw=new Set(["node_modules",".git",".boxel-history",".cache",".vscode","dist","build","tmp"]),dw=6;function pw(r,e){return r==="unchanged"&&e==="unchanged"||r==="deleted"&&e==="deleted"?null:r==="unchanged"&&e==="added"?"new-remote":r==="unchanged"&&e==="changed"?"modified-remote":r==="unchanged"&&e==="deleted"?"deleted-remote":r==="added"&&e==="unchanged"?"new-local":r==="changed"&&e==="unchanged"?"modified-local":r==="deleted"&&e==="unchanged"?"deleted-local":r==="changed"&&e==="changed"||r==="added"&&e==="added"||r==="changed"&&e==="added"||r==="added"&&e==="changed"||r==="changed"&&e==="deleted"||r==="deleted"&&e==="changed"?"conflict":r==="added"&&e==="deleted"?"new-local":r==="deleted"&&e==="added"?"new-remote":null}var Jn=class extends ie{constructor(t,n,i){super(t,i);this.statusOptions=t;this.loadedManifest=n}changes=[];pulled=[];hasError=!1;error;remoteMtimes=new Map;async sync(){let t,n;try{[t,this.remoteMtimes,n]=await Promise.all([this.getLocalFileListWithMtimes(),this.getRemoteMtimes(),this.getRemoteFileList()])}catch(a){this.hasError=!0,this.error=a instanceof Error?`Failed to fetch realm state: ${a.message}`:`Failed to fetch realm state: ${String(a)}`;return}if(n&&this.remoteMtimes.size===0&&n.size>0)for(let[a]of n)this.remoteMtimes.set(a,0);let i=new Map;for(let[a,l]of t)i.set(a,l.path);let o=new Map;await Promise.all(Array.from(i.entries()).map(async([a,l])=>{D(a)||o.set(a,await oe(l))}));let s=new Set;for(let a of i.keys())s.add(a);for(let a of this.remoteMtimes.keys())s.add(a);for(let a of Object.keys(this.loadedManifest.files))s.add(a);if(this.loadedManifest.remoteMtimes)for(let a of Object.keys(this.loadedManifest.remoteMtimes))s.add(a);for(let a of s){if(D(a))continue;let l=cr(a,o,this.loadedManifest),u=ur(a,this.remoteMtimes,this.loadedManifest),c=pw(l,u);c!==null&&this.changes.push({file:a,status:c})}this.changes.sort((a,l)=>a.file.localeCompare(l.file)),this.statusOptions.pull&&await this.performSafePull()}async performSafePull(){let t=this.changes.filter(i=>i.status==="new-remote"||i.status==="modified-remote");if(t.length===0)return;let n=[];for(let i of t){let o=st.join(this.options.localDir,i.file);try{await this.downloadFile(i.file,o),this.pulled.push(i.file);let s=await oe(o);this.loadedManifest.files[i.file]=s;let a=this.remoteMtimes.get(i.file);a!==void 0&&(this.loadedManifest.remoteMtimes=this.loadedManifest.remoteMtimes??{},this.loadedManifest.remoteMtimes[i.file]=a)}catch(s){this.hasError=!0;let a=s instanceof Error?s.message:String(s);n.push({file:i.file,message:a}),console.error(` ${h}\u2717 ${i.file}${f} (${a})`)}}n.length>0&&(this.error=`Failed to pull ${n.length} file(s): ${n.map(i=>`${i.file} (${i.message})`).join("; ")}`),this.pulled.length>0&&await Re(this.options.localDir,this.loadedManifest)}};async function cc(r,e){let t={localDir:r,realmUrl:"",changes:[],pulled:[],inSync:!1,hasError:!1},n=st.join(r,".boxel-sync.json");if(!await Ge(n))return{...t,hasError:!0,error:`No .boxel-sync.json found in ${r}. Run: boxel realm sync ${r} <realm-url>`};let i=await ye(r);if(!i)return{...t,hasError:!0,error:`Malformed .boxel-sync.json in ${r}`};let o;try{o=(await Ve.stat(n)).mtimeMs}catch{}let s;if(e.authenticator)s=e.authenticator;else{let l=de({realmUrl:i.realmUrl,realmSecretSeed:e.realmSecretSeed,profileManager:e.profileManager});if(!l.ok)return{...t,realmUrl:i.realmUrl,manifestMtime:o,hasError:!0,error:l.error};s=l.authenticator}let a=new Jn({realmUrl:i.realmUrl,localDir:r,pull:e.pull},i,s);return await a.sync(),{localDir:r,realmUrl:i.realmUrl,manifestMtime:o,changes:a.changes,pulled:a.pulled.slice().sort(),inSync:!a.hasError&&a.changes.length===0,hasError:a.hasError,error:a.error}}async function hw(r,e){let t=[];async function n(i,o){if(o>e)return;let s;try{s=await Ve.readdir(i,{withFileTypes:!0})}catch{return}if(s.some(l=>l.isFile()&&l.name===".boxel-sync.json")){t.push(i);return}for(let l of s)l.isDirectory()&&(mw.has(l.name)||await n(st.join(i,l.name),o+1))}return await n(r,0),t.sort(),t}async function gw(r,e){if(e.pull)return{rootDir:r,workspaces:[],hasError:!0,error:"Cannot use --pull with --all"};let t=process.env.BOXEL_STATUS_ALL_MAX_DEPTH,n=t!==void 0?Number(t):NaN,i=Number.isFinite(n)&&n>=0?n:dw,o=await hw(r,i),s=[],a=!1;for(let l of o){let u=st.join(l,".boxel-sync.json"),c;try{c=await Ve.readFile(u,"utf8")}catch{s.push({localDir:l,realmUrl:"",changes:[],pulled:[],inSync:!1,hasError:!0,skipped:"no-manifest"}),a=!0;continue}let m;try{m=JSON.parse(c)}catch{m=void 0}if(!Xn(m)){s.push({localDir:l,realmUrl:"",changes:[],pulled:[],inSync:!1,hasError:!0,skipped:"malformed"}),a=!0;continue}let d=await cc(l,{profileManager:e.profileManager,realmSecretSeed:e.realmSecretSeed,authenticator:e.authenticator}),p={...d};d.hasError&&(p.skipped="fetch-failed",a=!0),s.push(p)}return{rootDir:r,workspaces:s,hasError:a}}function yw(r){if(r.hasError&&r.error){console.error(`${h}Error:${f} ${r.error}`);return}if(console.log(`Realm: ${r.realmUrl}`),console.log(`Local: ${r.localDir}`),r.manifestMtime&&console.log(`${y}Manifest updated:${f} ${new Date(r.manifestMtime).toISOString()}`),console.log(""),r.changes.length===0){console.log(`${S}\u2713 In sync${f}`);return}let e={"new-remote":[],"modified-remote":[],"new-local":[],"modified-local":[],conflict:[],"deleted-local":[],"deleted-remote":[]};for(let t of r.changes)e[t.status].push(t.file);if(e["new-remote"].length>0){console.log(`${_}\u2193 New on remote (${e["new-remote"].length}):${f}`);for(let t of e["new-remote"])console.log(` + ${t}`);console.log("")}if(e["modified-remote"].length>0){console.log(`${_}\u2193 Modified on remote (${e["modified-remote"].length}):${f}`);for(let t of e["modified-remote"])console.log(` ~ ${t}`);console.log("")}if(e["new-local"].length>0){console.log(`${S}\u2191 New locally (${e["new-local"].length}):${f}`);for(let t of e["new-local"])console.log(` + ${t}`);console.log("")}if(e["modified-local"].length>0){console.log(`${S}\u2191 Modified locally (${e["modified-local"].length}):${f}`);for(let t of e["modified-local"])console.log(` ~ ${t}`);console.log("")}if(e.conflict.length>0){console.log(`${C}\u26A0 Conflicts (${e.conflict.length}):${f}`);for(let t of e.conflict)console.log(` ! ${t}`);console.log("")}if(e["deleted-local"].length>0){console.log(`${h}- Deleted locally (${e["deleted-local"].length}):${f}`);for(let t of e["deleted-local"])console.log(` - ${t}`);console.log("")}if(e["deleted-remote"].length>0){console.log(`${h}- Deleted on remote (${e["deleted-remote"].length}):${f}`);for(let t of e["deleted-remote"])console.log(` - ${t}`);console.log("")}if(r.pulled.length>0){console.log(`${_}Pulled ${r.pulled.length} file(s):${f}`);for(let t of r.pulled)console.log(` \u2713 ${t}`)}}function ww(r){if(r.error){console.error(`${h}Error:${f} ${r.error}`);return}if(r.workspaces.length===0){console.log(`No .boxel-sync.json directories found under ${r.rootDir}.`);return}for(let e of r.workspaces){if(e.skipped){console.log(`${C}${e.localDir}${f} [${e.skipped}]`),e.error&&console.log(` ${y}${e.error}${f}`),console.log("");continue}let t={newRemote:0,modRemote:0,newLocal:0,modLocal:0,conflict:0,delLocal:0,delRemote:0};for(let n of e.changes)n.status==="new-remote"?t.newRemote++:n.status==="modified-remote"?t.modRemote++:n.status==="new-local"?t.newLocal++:n.status==="modified-local"?t.modLocal++:n.status==="conflict"?t.conflict++:n.status==="deleted-local"?t.delLocal++:n.status==="deleted-remote"&&t.delRemote++;if(console.log(`${e.localDir} ${y}${e.realmUrl}${f}`),e.inSync)console.log(` ${S}\u2713 in sync${f}`);else{let n=[];t.newRemote>0&&n.push(`${_}\u2193+${t.newRemote}${f}`),t.modRemote>0&&n.push(`${_}\u2193~${t.modRemote}${f}`),t.newLocal>0&&n.push(`${S}\u2191+${t.newLocal}${f}`),t.modLocal>0&&n.push(`${S}\u2191~${t.modLocal}${f}`),t.conflict>0&&n.push(`${C}\u26A0${t.conflict}${f}`),t.delLocal>0&&n.push(`${h}-L${t.delLocal}${f}`),t.delRemote>0&&n.push(`${h}-R${t.delRemote}${f}`),console.log(` ${n.join(" ")}`)}console.log("")}}function uc(r){r.command("status").aliases(["st"]).description("Show pending changes between a local sync dir and its realm").argument("[local-dir]","Local sync directory (defaults to current working directory)").option("--pull","Download safe remote changes and update manifest").option("--all","Recursively report all .boxel-sync.json dirs under the current directory").option("--realm-secret-seed","Administrative auth: prompt for a realm secret seed and mint a JWT locally instead of using a Matrix profile (env: BOXEL_REALM_SECRET_SEED)").action(async(e,t)=>{let n=await me(t.realmSecretSeed===!0);if(t.all){t.pull&&(console.error(`${h}Error:${f} Cannot use --pull with --all`),process.exit(1));let o=await gw(e??process.cwd(),{all:!0,realmSecretSeed:n});ww(o),o.hasError&&process.exit(2);return}let i=await cc(e??process.cwd(),{pull:t.pull,realmSecretSeed:n});yw(i),i.hasError&&process.exit(i.pulled.length>0?2:1)})}var Qn=O(require("path"));var Zn=class extends ie{constructor(t,n){super(t,n);this.syncOptions=t}hasError=!1;pushedFiles=[];pulledFiles=[];remoteDeletedFiles=[];localDeletedFiles=[];skippedConflicts=[];get conflictStrategy(){return this.syncOptions.preferLocal?"prefer-local":this.syncOptions.preferRemote?"prefer-remote":this.syncOptions.preferNewest?"prefer-newest":null}async sync(){console.log(`Starting sync between ${this.options.localDir} and ${this.options.realmUrl}`),console.log("Testing realm access...");let t;try{t=await this.getRemoteFileList("")}catch(b){throw console.error("Failed to access realm:",b),new Error("Cannot proceed with sync: Authentication or access failed. Please check your credentials and realm permissions.")}console.log("Realm access verified");let[n,i,o]=await Promise.all([this.getLocalFileListWithMtimes(),this.getRemoteMtimes(),ye(this.options.localDir)]),s=new Map;for(let[b,R]of n)s.set(b,R.path);if(i.size===0&&t&&t.size>0){console.log("Remote mtimes unavailable, falling back to file listing for remote detection");for(let[b]of t)i.set(b,0)}console.log(`Found ${s.size} local files`),console.log(`Found ${i.size} remote files`),o&&o.realmUrl!==this.normalizedRealmUrl&&console.warn(`${C}Warning:${f} Manifest realm URL (${o.realmUrl}) differs from target (${this.normalizedRealmUrl}). Treating as first sync.`);let a=o&&o.realmUrl===this.normalizedRealmUrl?o:null,l=new Map;await Promise.all(Array.from(s.entries()).map(async([b,R])=>{D(b)||l.set(b,await oe(R))}));let u=new Set;for(let b of s.keys())u.add(b);for(let b of i.keys())u.add(b);if(a){for(let b of Object.keys(a.files))u.add(b);if(a.remoteMtimes)for(let b of Object.keys(a.remoteMtimes))u.add(b)}let c=[];for(let b of u){if(D(b))continue;let R=cr(b,l,a),k=ur(b,i,a),F=ac(R,k,this.syncOptions);c.push({relativePath:b,localStatus:R,remoteStatus:k,action:F})}let m=[],d=[],p=[],w=[],x=[],Q=0;for(let b of c)switch(b.action){case"push":m.push(b.relativePath);break;case"pull":d.push(b.relativePath);break;case"push-delete":p.push(b.relativePath);break;case"pull-delete":w.push(b.relativePath);break;case"conflict":x.push(b);break;case"noop":Q++;break}for(let b of x)switch(lc(b,n,i,this.conflictStrategy)){case"push":m.push(b.relativePath);break;case"pull":d.push(b.relativePath);break;case"push-delete":p.push(b.relativePath);break;case"pull-delete":w.push(b.relativePath);break;case"noop":break;default:this.skippedConflicts.push(b.relativePath);break}if(console.log(`
92
- ${y}Sync plan:${f}`),m.length>0&&console.log(` ${S}\u2191 Push:${f} ${m.length} file(s)`),d.length>0&&console.log(` ${_}\u2193 Pull:${f} ${d.length} file(s)`),p.length>0&&console.log(` ${h}\u2191 Delete remote:${f} ${p.length} file(s)`),w.length>0&&console.log(` ${h}\u2193 Delete local:${f} ${w.length} file(s)`),this.skippedConflicts.length>0){console.log(` ${C}\u26A0 Conflicts skipped:${f} ${this.skippedConflicts.length} file(s)`);for(let b of this.skippedConflicts)console.log(` ${b}`);console.log(` ${y}Use --prefer-local, --prefer-remote, or --prefer-newest to resolve.${f}`)}if(Q>0&&console.log(` ${y}Unchanged: ${Q} file(s)${f}`),m.length+d.length+p.length+w.length===0){console.log(`
90
+ Checkpoint created: ${u.shortHash} ${c} ${u.message}`)}}console.log("Pull completed")}};function rc(r){r.command("pull").description("Pull files from a Boxel realm to a local directory").argument("<realm-url>","The URL of the source realm (e.g., https://app.boxel.ai/demo/)").argument("<local-dir>","The local directory to sync files to").option("--delete","Delete local files that do not exist in the realm").option("--dry-run","Show what would be done without making changes").option("--realm-secret-seed","Administrative auth: prompt for a realm secret seed and mint a JWT locally instead of using a Matrix profile (env: BOXEL_REALM_SECRET_SEED)").action(async(e,t,n)=>{let i=await me(n.realmSecretSeed===!0),o=await lw(e,t,{delete:n.delete,dryRun:n.dryRun,realmSecretSeed:i});o.error&&(console.error(`Error: ${o.error}`),process.exit(o.files.length>0?2:1)),console.log("Pull completed successfully")})}async function lw(r,e,t){let n;if(t.authenticator)n=t.authenticator;else{let i=de({realmUrl:r,realmSecretSeed:t.realmSecretSeed,profileManager:t.profileManager});if(!i.ok)return{files:[],error:i.error};n=i.authenticator}try{let i=new Yn({realmUrl:r,localDir:e,deleteLocal:t.delete,dryRun:t.dryRun},n);return await i.sync(),i.hasError?{files:i.downloadedFiles.sort(),error:"Pull completed with errors. Some files may not have been downloaded."}:{files:i.downloadedFiles.sort()}}catch(i){return{files:[],error:`Pull failed: ${i instanceof Error?i.message:String(i)}`}}}var Pe=O(require("fs/promises")),Xn=O(require("path")),nc=O(require("crypto"));function zn(r){if(typeof r!="object"||r===null)return!1;let e=r;if(typeof e.realmUrl!="string"||typeof e.files!="object"||e.files===null)return!1;for(let t of Object.values(e.files))if(typeof t!="string")return!1;if(e.remoteMtimes!==void 0){if(typeof e.remoteMtimes!="object"||e.remoteMtimes===null)return!1;for(let t of Object.values(e.remoteMtimes))if(typeof t!="number")return!1}return!0}async function Ve(r){try{return await Pe.access(r),!0}catch{return!1}}async function Z(r){let e=await Pe.readFile(r);return nc.createHash("md5").update(e).digest("hex")}async function pe(r){let e=Xn.join(r,".boxel-sync.json"),t;try{t=await Pe.readFile(e,"utf8")}catch(i){if(i.code==="ENOENT")return null;throw i}let n;try{n=JSON.parse(t)}catch{return null}return zn(n)?n:(console.warn("Warning: .boxel-sync.json is malformed or has an unexpected shape; falling back to a full upload."),null)}async function Se(r,e){let t=Xn.join(r,".boxel-sync.json");await Pe.writeFile(t,JSON.stringify(e,null,2))}var cw=new Set(["index.json","realm.json"]),Jn=class extends oe{constructor(t,n){super(t,n);this.pushOptions=t}hasError=!1;async sync(){console.log(`Starting push from ${this.options.localDir} to ${this.options.realmUrl}`),console.log("Testing realm access...");let t;try{t=await this.getRemoteFileList("")}catch(c){throw console.error("Failed to access realm:",c),new Error("Cannot proceed with push: Authentication or access failed. Please check your credentials and realm permissions.")}console.log("Realm access verified");let n=await this.getLocalFileList();console.log(`Found ${n.size} files in local directory`);let i=await pe(this.options.localDir),o={realmUrl:this.normalizedRealmUrl,files:{},remoteMtimes:{}},s=new Map,a=new Set;if(!this.pushOptions.force&&i!==null&&i.realmUrl===this.normalizedRealmUrl){console.log("Checking for changed files...");let c=0,[m,d]=await Promise.all([this.getRemoteMtimes(),Promise.all(Array.from(n.entries()).map(async([p,w])=>{if(D(p))return{relativePath:p,localPath:w,currentHash:"",protected:!0};let v=await Z(w);return{relativePath:p,localPath:w,currentHash:v,protected:!1}}))]);for(let p of d){if(p.protected){c++;continue}let w=i.files[p.relativePath],v=i.remoteMtimes?.[p.relativePath],B=m.get(p.relativePath),we=w!==p.currentHash,b=w!==void 0&&!t.has(p.relativePath),R=v!==void 0&&B!==void 0&&B!==v;we||b||R?(s.set(p.relativePath,p.localPath),!we&&(b||R)&&a.add(p.relativePath)):(c++,o.files[p.relativePath]=p.currentHash,v!==void 0&&(o.remoteMtimes[p.relativePath]=v))}if(c>0&&console.log(`Skipping ${c} unchanged files`),a.size>0){let p=Array.from(a),w=p.slice(0,5).join(", "),v=p.length>5?", ...":"";console.warn(`Warning: ${a.size} file(s) changed on the realm since your last push; your local versions will overwrite them: ${w}${v}`)}}else{this.pushOptions.force?console.log("Force mode: uploading all files"):console.log(i?"Realm URL changed, will upload all files":"No sync manifest found, will upload all files");for(let[c,m]of n)D(c)||s.set(c,m)}let u=!1;if(s.size===0)console.log("No files to upload - everything is up to date");else{console.log(`Uploading ${s.size} file(s) via /_atomic...`);let c=new Set,m=this.pushOptions.force||!i;for(let p of s.keys())if(m)t.has(p)||c.add(p);else{let w=i.files[p]!==void 0,v=w&&!t.has(p);(!w||v)&&c.add(p)}let d=await this.uploadFilesAtomic(s,c);if(d.error){u=!0,this.hasError=!0,console.error(d.error.message);for(let p of d.error.perFile){let w;p.status===409?w=`${p.path} was created on the realm concurrently \u2014 run with --force to overwrite.`:p.status===404?w=`${p.path} was removed from the realm concurrently \u2014 run with --force to re-create it from your local copy.`:w=`${p.path}: ${p.title}`,console.error(` ${w}`)}}else if(d.succeeded.length>0){let p=await Promise.all(d.succeeded.map(async w=>({rel:w,hash:await Z(s.get(w))})));for(let{rel:w,hash:v}of p)o.files[w]=v}}if(this.pushOptions.deleteRemote){let c=new Set(t.keys()),m=[];for(let d of c){if(D(d)){c.delete(d);continue}cw.has(d)&&(c.delete(d),m.push(d))}for(let d of n.keys())c.delete(d);if(m.length>0&&console.log(`Skipping ${m.length} realm-managed remote artifact(s): ${m.join(", ")}`),c.size>0){let d=Array.from(c).sort();console.log(`Deleting ${d.length} remote files that don't exist locally: ${d.join(", ")}`);for(let p of d)try{await this.deleteFile(p)}catch(w){this.hasError=!0,console.error(`Error deleting ${p}:`,w)}}}if(!this.options.dryRun&&!u&&s.size>0)try{let c=await this.getRemoteMtimes();for(let m of Object.keys(o.files)){let d=c.get(m);d!==void 0&&(o.remoteMtimes[m]=d)}}catch(c){console.warn("Could not refresh remote mtimes after upload:",c)}if(o.remoteMtimes&&Object.keys(o.remoteMtimes).length===0&&delete o.remoteMtimes,!this.options.dryRun&&!u&&await Se(this.options.localDir,o),!this.options.dryRun&&s.size>0&&!u){let c=new U(this.options.localDir),m=Array.from(s.keys()).map(p=>({file:p,status:"modified"})),d=await c.createCheckpoint("local",m);if(d){let p=d.isMajor?"[MAJOR]":"[minor]";console.log(`
91
+ Checkpoint created: ${d.shortHash} ${p} ${d.message}`)}}console.log("Push completed")}};function ic(r){r.command("push").description("Push local files to a Boxel realm").argument("<local-dir>","The local directory containing files to sync").argument("<realm-url>","The URL of the target realm (e.g., https://app.boxel.ai/demo/)").option("--delete","Delete remote files that do not exist locally").option("--dry-run","Show what would be done without making changes").option("--force","Upload all files, even if unchanged").option("--realm-secret-seed","Administrative auth: prompt for a realm secret seed and mint a JWT locally instead of using a Matrix profile (env: BOXEL_REALM_SECRET_SEED)").action(async(e,t,n)=>{let i=await me(n.realmSecretSeed===!0);await uw(e,t,{delete:n.delete,dryRun:n.dryRun,force:n.force,realmSecretSeed:i})})}async function uw(r,e,t){let n;if(t.authenticator)n=t.authenticator;else{let i=de({realmUrl:e,realmSecretSeed:t.realmSecretSeed,profileManager:t.profileManager});i.ok||(console.error(`Error: ${i.error}`),process.exit(1)),n=i.authenticator}await Ve(r)||(console.error(`Local directory does not exist: ${r}`),process.exit(1));try{let i=new Jn({realmUrl:e,localDir:r,deleteRemote:t.delete,dryRun:t.dryRun,force:t.force},n);await i.sync(),i.hasError?(console.log("Push did not complete successfully. View logs for details"),process.exit(2)):console.log("Push completed successfully")}catch(i){console.error("Push failed:",i),process.exit(1)}}async function oc(r){let e=P(r.realmUrl.trim()),t=r.profileManager??A(),n=t.getActiveProfile();if(!n)return{realmUrl:e,removed:!1,serverDeleted:!1,unlinked:!1,previousCount:0,nextCount:0,error:M};let i;try{i=await t.getUserRealms()}catch(d){return{realmUrl:e,removed:!1,serverDeleted:!1,unlinked:!1,previousCount:0,nextCount:0,error:`Failed to load realm list: ${d instanceof Error?d.message:String(d)}`}}let o=i.map(P),s=o.length,a=o.filter(d=>d===e).length;if(a===0)return{realmUrl:e,removed:!1,serverDeleted:!1,unlinked:!1,previousCount:s,nextCount:s,notInList:!0,error:"Realm is not in app.boxel.realms. Nothing to remove."};let l=s-a;if(r.dryRun)return{realmUrl:e,removed:!1,serverDeleted:!1,unlinked:!1,previousCount:s,nextCount:l};let u=n.profile.realmServerUrl.replace(/\/$/,""),c;try{c=await t.authedRealmServerFetch(`${u}/_delete-realm`,{method:"DELETE",headers:{"Content-Type":"application/vnd.api+json"},body:JSON.stringify({data:{type:"realm",id:e}})})}catch(d){return{realmUrl:e,removed:!1,serverDeleted:!1,unlinked:!1,previousCount:s,nextCount:s,error:`Failed to reach realm server: ${d instanceof Error?d.message:String(d)}`}}if(!c.ok){let d=await fw(c),p=c.status===403?`You do not own this realm and cannot delete it on the server. Server returned 403: ${d}`:`Realm server returned ${c.status}: ${d}`;return{realmUrl:e,removed:!1,serverDeleted:!1,unlinked:!1,previousCount:s,nextCount:s,error:p}}let m;try{m=await t.removeFromUserRealms(e)}catch(d){return{realmUrl:e,removed:!1,serverDeleted:!0,unlinked:!1,previousCount:s,nextCount:s,error:`Server delete succeeded, but Matrix unlink failed: ${d instanceof Error?d.message:String(d)}`}}return m?{realmUrl:e,removed:!0,serverDeleted:!0,unlinked:m,previousCount:s,nextCount:l}:{realmUrl:e,removed:!1,serverDeleted:!0,unlinked:!1,previousCount:s,nextCount:s,error:"Server delete succeeded, but Matrix account_data did not contain the URL by the time we PUT (concurrent edit?). Server-side files are gone; please refresh and check your realm list."}}async function fw(r){try{return await r.text()}catch{return"<no response body>"}}function sc(r){r.command("remove").description("Remove a realm \u2014 deletes server-side files and unlinks it from your realm list").argument("<realm-url>","realm URL to remove").option("-y, --yes","Skip the interactive confirmation prompt").option("--dry-run","Preview the change without writing to Matrix").action(async(e,t)=>{let n=P(e.trim()),i=await oc({realmUrl:n,dryRun:!0});if(i.error&&!i.notInList&&(console.error(`${h}Error:${f} ${i.error}`),process.exit(1)),i.notInList&&(console.error(`${h}Error:${f} ${i.error}`),process.exit(1)),console.log(`Remove target: ${_}${i.realmUrl}${f}`),console.log(`${g}app.boxel.realms: ${i.previousCount} -> ${i.nextCount}${f}`),t.dryRun){console.log(`${g}[DRY RUN] No server delete or Matrix changes sent.${f}`);return}if(!t.yes){process.stdin.isTTY||(console.error(`${h}Error:${f} stdin is not a TTY. Pass --yes to confirm in non-interactive mode.`),process.exit(1));let s=await Q("This will permanently delete the realm files, indexer state, and registry entry on the server. Proceed? (y/N) ");if(!/^y/i.test(s)){console.log(`${g}Cancelled.${f}`);return}}let o=await oc({realmUrl:n});(o.error||!o.removed)&&(console.error(`${h}Error:${f} ${o.error??"Removal did not complete."}`),o.serverDeleted&&!o.unlinked&&console.error(`${g}The realm is gone, but your account_data still references ${o.realmUrl}.${f}`),process.exit(1)),console.log(`${S}Removed:${f} ${_}${o.realmUrl}${f}`)})}var He=O(require("fs/promises")),at=O(require("path"));function lr(r,e,t){let n=e.has(r),i=t?.files[r]!==void 0;return n&&i?e.get(r)===t.files[r]?"unchanged":"changed":n&&!i?"added":!n&&i?"deleted":"unchanged"}function cr(r,e,t){let n=e.has(r),i=t?.remoteMtimes?.[r]!==void 0,o=t?.files[r]!==void 0,s=i||o;return n&&i?e.get(r)===t.remoteMtimes[r]?"unchanged":"changed":n&&o?"changed":n&&!s?"added":!n&&s?"deleted":"unchanged"}function ac(r,e,t){return r==="unchanged"&&e==="unchanged"?"noop":r==="changed"&&e==="unchanged"?"push":r==="unchanged"&&e==="changed"?"pull":r==="added"&&e==="unchanged"?"push":r==="unchanged"&&e==="added"?"pull":r==="changed"&&e==="changed"||r==="added"&&e==="added"||r==="changed"&&e==="added"||r==="added"&&e==="changed"?"conflict":r==="deleted"&&e==="unchanged"?t.deleteSync||t.preferLocal?"push-delete":"noop":r==="unchanged"&&e==="deleted"?t.deleteSync||t.preferRemote?"pull-delete":"noop":r==="deleted"&&e==="changed"||r==="changed"&&e==="deleted"?"conflict":r==="deleted"&&e==="deleted"?"noop":r==="added"&&e==="deleted"?"push":r==="deleted"&&e==="added"?"pull":"noop"}function lc(r,e,t,n){let{localStatus:i,remoteStatus:o,relativePath:s}=r;if(!n)return null;switch(n){case"prefer-local":return i==="deleted"?"push-delete":"push";case"prefer-remote":return o==="deleted"?"pull-delete":"pull";case"prefer-newest":{if(i==="deleted"&&o==="changed")return"pull";if(i==="changed"&&o==="deleted")return"push";let a=e.get(s),l=t.get(s);return a&&l!==void 0?a.mtime>l*1e3?"push":"pull":"push"}}}var mw=new Set(["node_modules",".git",".boxel-history",".cache",".vscode","dist","build","tmp"]),dw=6;function pw(r,e){return r==="unchanged"&&e==="unchanged"||r==="deleted"&&e==="deleted"?null:r==="unchanged"&&e==="added"?"new-remote":r==="unchanged"&&e==="changed"?"modified-remote":r==="unchanged"&&e==="deleted"?"deleted-remote":r==="added"&&e==="unchanged"?"new-local":r==="changed"&&e==="unchanged"?"modified-local":r==="deleted"&&e==="unchanged"?"deleted-local":r==="changed"&&e==="changed"||r==="added"&&e==="added"||r==="changed"&&e==="added"||r==="added"&&e==="changed"||r==="changed"&&e==="deleted"||r==="deleted"&&e==="changed"?"conflict":r==="added"&&e==="deleted"?"new-local":r==="deleted"&&e==="added"?"new-remote":null}var Kn=class extends oe{constructor(t,n,i){super(t,i);this.statusOptions=t;this.loadedManifest=n}changes=[];pulled=[];hasError=!1;error;remoteMtimes=new Map;async sync(){let t,n;try{[t,this.remoteMtimes,n]=await Promise.all([this.getLocalFileListWithMtimes(),this.getRemoteMtimes(),this.getRemoteFileList()])}catch(a){this.hasError=!0,this.error=a instanceof Error?`Failed to fetch realm state: ${a.message}`:`Failed to fetch realm state: ${String(a)}`;return}if(n&&this.remoteMtimes.size===0&&n.size>0)for(let[a]of n)this.remoteMtimes.set(a,0);let i=new Map;for(let[a,l]of t)i.set(a,l.path);let o=new Map;await Promise.all(Array.from(i.entries()).map(async([a,l])=>{D(a)||o.set(a,await Z(l))}));let s=new Set;for(let a of i.keys())s.add(a);for(let a of this.remoteMtimes.keys())s.add(a);for(let a of Object.keys(this.loadedManifest.files))s.add(a);if(this.loadedManifest.remoteMtimes)for(let a of Object.keys(this.loadedManifest.remoteMtimes))s.add(a);for(let a of s){if(D(a))continue;let l=lr(a,o,this.loadedManifest),u=cr(a,this.remoteMtimes,this.loadedManifest),c=pw(l,u);c!==null&&this.changes.push({file:a,status:c})}this.changes.sort((a,l)=>a.file.localeCompare(l.file)),this.statusOptions.pull&&await this.performSafePull()}async performSafePull(){let t=this.changes.filter(i=>i.status==="new-remote"||i.status==="modified-remote");if(t.length===0)return;let n=[];for(let i of t){let o=at.join(this.options.localDir,i.file);try{await this.downloadFile(i.file,o),this.pulled.push(i.file);let s=await Z(o);this.loadedManifest.files[i.file]=s;let a=this.remoteMtimes.get(i.file);a!==void 0&&(this.loadedManifest.remoteMtimes=this.loadedManifest.remoteMtimes??{},this.loadedManifest.remoteMtimes[i.file]=a)}catch(s){this.hasError=!0;let a=s instanceof Error?s.message:String(s);n.push({file:i.file,message:a}),console.error(` ${h}\u2717 ${i.file}${f} (${a})`)}}n.length>0&&(this.error=`Failed to pull ${n.length} file(s): ${n.map(i=>`${i.file} (${i.message})`).join("; ")}`),this.pulled.length>0&&await Se(this.options.localDir,this.loadedManifest)}};async function cc(r,e){let t={localDir:r,realmUrl:"",changes:[],pulled:[],inSync:!1,hasError:!1},n=at.join(r,".boxel-sync.json");if(!await Ve(n))return{...t,hasError:!0,error:`No .boxel-sync.json found in ${r}. Run: boxel realm sync ${r} <realm-url>`};let i=await pe(r);if(!i)return{...t,hasError:!0,error:`Malformed .boxel-sync.json in ${r}`};let o;try{o=(await He.stat(n)).mtimeMs}catch{}let s;if(e.authenticator)s=e.authenticator;else{let l=de({realmUrl:i.realmUrl,realmSecretSeed:e.realmSecretSeed,profileManager:e.profileManager});if(!l.ok)return{...t,realmUrl:i.realmUrl,manifestMtime:o,hasError:!0,error:l.error};s=l.authenticator}let a=new Kn({realmUrl:i.realmUrl,localDir:r,pull:e.pull},i,s);return await a.sync(),{localDir:r,realmUrl:i.realmUrl,manifestMtime:o,changes:a.changes,pulled:a.pulled.slice().sort(),inSync:!a.hasError&&a.changes.length===0,hasError:a.hasError,error:a.error}}async function hw(r,e){let t=[];async function n(i,o){if(o>e)return;let s;try{s=await He.readdir(i,{withFileTypes:!0})}catch{return}if(s.some(l=>l.isFile()&&l.name===".boxel-sync.json")){t.push(i);return}for(let l of s)l.isDirectory()&&(mw.has(l.name)||await n(at.join(i,l.name),o+1))}return await n(r,0),t.sort(),t}async function gw(r,e){if(e.pull)return{rootDir:r,workspaces:[],hasError:!0,error:"Cannot use --pull with --all"};let t=process.env.BOXEL_STATUS_ALL_MAX_DEPTH,n=t!==void 0?Number(t):NaN,i=Number.isFinite(n)&&n>=0?n:dw,o=await hw(r,i),s=[],a=!1;for(let l of o){let u=at.join(l,".boxel-sync.json"),c;try{c=await He.readFile(u,"utf8")}catch{s.push({localDir:l,realmUrl:"",changes:[],pulled:[],inSync:!1,hasError:!0,skipped:"no-manifest"}),a=!0;continue}let m;try{m=JSON.parse(c)}catch{m=void 0}if(!zn(m)){s.push({localDir:l,realmUrl:"",changes:[],pulled:[],inSync:!1,hasError:!0,skipped:"malformed"}),a=!0;continue}let d=await cc(l,{profileManager:e.profileManager,realmSecretSeed:e.realmSecretSeed,authenticator:e.authenticator}),p={...d};d.hasError&&(p.skipped="fetch-failed",a=!0),s.push(p)}return{rootDir:r,workspaces:s,hasError:a}}function yw(r){if(r.hasError&&r.error){console.error(`${h}Error:${f} ${r.error}`);return}if(console.log(`Realm: ${r.realmUrl}`),console.log(`Local: ${r.localDir}`),r.manifestMtime&&console.log(`${g}Manifest updated:${f} ${new Date(r.manifestMtime).toISOString()}`),console.log(""),r.changes.length===0){console.log(`${S}\u2713 In sync${f}`);return}let e={"new-remote":[],"modified-remote":[],"new-local":[],"modified-local":[],conflict:[],"deleted-local":[],"deleted-remote":[]};for(let t of r.changes)e[t.status].push(t.file);if(e["new-remote"].length>0){console.log(`${_}\u2193 New on remote (${e["new-remote"].length}):${f}`);for(let t of e["new-remote"])console.log(` + ${t}`);console.log("")}if(e["modified-remote"].length>0){console.log(`${_}\u2193 Modified on remote (${e["modified-remote"].length}):${f}`);for(let t of e["modified-remote"])console.log(` ~ ${t}`);console.log("")}if(e["new-local"].length>0){console.log(`${S}\u2191 New locally (${e["new-local"].length}):${f}`);for(let t of e["new-local"])console.log(` + ${t}`);console.log("")}if(e["modified-local"].length>0){console.log(`${S}\u2191 Modified locally (${e["modified-local"].length}):${f}`);for(let t of e["modified-local"])console.log(` ~ ${t}`);console.log("")}if(e.conflict.length>0){console.log(`${C}\u26A0 Conflicts (${e.conflict.length}):${f}`);for(let t of e.conflict)console.log(` ! ${t}`);console.log("")}if(e["deleted-local"].length>0){console.log(`${h}- Deleted locally (${e["deleted-local"].length}):${f}`);for(let t of e["deleted-local"])console.log(` - ${t}`);console.log("")}if(e["deleted-remote"].length>0){console.log(`${h}- Deleted on remote (${e["deleted-remote"].length}):${f}`);for(let t of e["deleted-remote"])console.log(` - ${t}`);console.log("")}if(r.pulled.length>0){console.log(`${_}Pulled ${r.pulled.length} file(s):${f}`);for(let t of r.pulled)console.log(` \u2713 ${t}`)}}function ww(r){if(r.error){console.error(`${h}Error:${f} ${r.error}`);return}if(r.workspaces.length===0){console.log(`No .boxel-sync.json directories found under ${r.rootDir}.`);return}for(let e of r.workspaces){if(e.skipped){console.log(`${C}${e.localDir}${f} [${e.skipped}]`),e.error&&console.log(` ${g}${e.error}${f}`),console.log("");continue}let t={newRemote:0,modRemote:0,newLocal:0,modLocal:0,conflict:0,delLocal:0,delRemote:0};for(let n of e.changes)n.status==="new-remote"?t.newRemote++:n.status==="modified-remote"?t.modRemote++:n.status==="new-local"?t.newLocal++:n.status==="modified-local"?t.modLocal++:n.status==="conflict"?t.conflict++:n.status==="deleted-local"?t.delLocal++:n.status==="deleted-remote"&&t.delRemote++;if(console.log(`${e.localDir} ${g}${e.realmUrl}${f}`),e.inSync)console.log(` ${S}\u2713 in sync${f}`);else{let n=[];t.newRemote>0&&n.push(`${_}\u2193+${t.newRemote}${f}`),t.modRemote>0&&n.push(`${_}\u2193~${t.modRemote}${f}`),t.newLocal>0&&n.push(`${S}\u2191+${t.newLocal}${f}`),t.modLocal>0&&n.push(`${S}\u2191~${t.modLocal}${f}`),t.conflict>0&&n.push(`${C}\u26A0${t.conflict}${f}`),t.delLocal>0&&n.push(`${h}-L${t.delLocal}${f}`),t.delRemote>0&&n.push(`${h}-R${t.delRemote}${f}`),console.log(` ${n.join(" ")}`)}console.log("")}}function uc(r){r.command("status").aliases(["st"]).description("Show pending changes between a local sync dir and its realm").argument("[local-dir]","Local sync directory (defaults to current working directory)").option("--pull","Download safe remote changes and update manifest").option("--all","Recursively report all .boxel-sync.json dirs under the current directory").option("--realm-secret-seed","Administrative auth: prompt for a realm secret seed and mint a JWT locally instead of using a Matrix profile (env: BOXEL_REALM_SECRET_SEED)").action(async(e,t)=>{let n=await me(t.realmSecretSeed===!0);if(t.all){t.pull&&(console.error(`${h}Error:${f} Cannot use --pull with --all`),process.exit(1));let o=await gw(e??process.cwd(),{all:!0,realmSecretSeed:n});ww(o),o.hasError&&process.exit(2);return}let i=await cc(e??process.cwd(),{pull:t.pull,realmSecretSeed:n});yw(i),i.hasError&&process.exit(i.pulled.length>0?2:1)})}var Zn=O(require("path"));var ei=class extends oe{constructor(t,n){super(t,n);this.syncOptions=t}hasError=!1;pushedFiles=[];pulledFiles=[];remoteDeletedFiles=[];localDeletedFiles=[];skippedConflicts=[];get conflictStrategy(){return this.syncOptions.preferLocal?"prefer-local":this.syncOptions.preferRemote?"prefer-remote":this.syncOptions.preferNewest?"prefer-newest":null}async sync(){console.log(`Starting sync between ${this.options.localDir} and ${this.options.realmUrl}`),console.log("Testing realm access...");let t;try{t=await this.getRemoteFileList("")}catch(b){throw console.error("Failed to access realm:",b),new Error("Cannot proceed with sync: Authentication or access failed. Please check your credentials and realm permissions.")}console.log("Realm access verified");let[n,i,o]=await Promise.all([this.getLocalFileListWithMtimes(),this.getRemoteMtimes(),pe(this.options.localDir)]),s=new Map;for(let[b,R]of n)s.set(b,R.path);if(i.size===0&&t&&t.size>0){console.log("Remote mtimes unavailable, falling back to file listing for remote detection");for(let[b]of t)i.set(b,0)}console.log(`Found ${s.size} local files`),console.log(`Found ${i.size} remote files`),o&&o.realmUrl!==this.normalizedRealmUrl&&console.warn(`${C}Warning:${f} Manifest realm URL (${o.realmUrl}) differs from target (${this.normalizedRealmUrl}). Treating as first sync.`);let a=o&&o.realmUrl===this.normalizedRealmUrl?o:null,l=new Map;await Promise.all(Array.from(s.entries()).map(async([b,R])=>{D(b)||l.set(b,await Z(R))}));let u=new Set;for(let b of s.keys())u.add(b);for(let b of i.keys())u.add(b);if(a){for(let b of Object.keys(a.files))u.add(b);if(a.remoteMtimes)for(let b of Object.keys(a.remoteMtimes))u.add(b)}let c=[];for(let b of u){if(D(b))continue;let R=lr(b,l,a),k=cr(b,i,a),F=ac(R,k,this.syncOptions);c.push({relativePath:b,localStatus:R,remoteStatus:k,action:F})}let m=[],d=[],p=[],w=[],v=[],B=0;for(let b of c)switch(b.action){case"push":m.push(b.relativePath);break;case"pull":d.push(b.relativePath);break;case"push-delete":p.push(b.relativePath);break;case"pull-delete":w.push(b.relativePath);break;case"conflict":v.push(b);break;case"noop":B++;break}for(let b of v)switch(lc(b,n,i,this.conflictStrategy)){case"push":m.push(b.relativePath);break;case"pull":d.push(b.relativePath);break;case"push-delete":p.push(b.relativePath);break;case"pull-delete":w.push(b.relativePath);break;case"noop":break;default:this.skippedConflicts.push(b.relativePath);break}if(console.log(`
92
+ ${g}Sync plan:${f}`),m.length>0&&console.log(` ${S}\u2191 Push:${f} ${m.length} file(s)`),d.length>0&&console.log(` ${_}\u2193 Pull:${f} ${d.length} file(s)`),p.length>0&&console.log(` ${h}\u2191 Delete remote:${f} ${p.length} file(s)`),w.length>0&&console.log(` ${h}\u2193 Delete local:${f} ${w.length} file(s)`),this.skippedConflicts.length>0){console.log(` ${C}\u26A0 Conflicts skipped:${f} ${this.skippedConflicts.length} file(s)`);for(let b of this.skippedConflicts)console.log(` ${b}`);console.log(` ${g}Use --prefer-local, --prefer-remote, or --prefer-newest to resolve.${f}`)}if(B>0&&console.log(` ${g}Unchanged: ${B} file(s)${f}`),m.length+d.length+p.length+w.length===0){console.log(`
93
93
  Everything is up to date`),!this.options.dryRun&&!a&&this.skippedConflicts.length===0&&await this.writeManifest(l,i);return}if(d.length>0){console.log(`
94
- Pulling ${d.length} file(s)...`);let b=await Promise.all(d.map(R=>this.remoteLimit(async()=>{try{let k=Qn.join(this.options.localDir,R);return await this.downloadFile(R,k),R}catch(k){return this.hasError=!0,console.error(`Error downloading ${R}:`,k),null}})));this.pulledFiles.push(...b.filter(R=>R!==null))}if(m.length>0){console.log(`
95
- Pushing ${m.length} file(s)...`);let b=new Map;for(let F of m){let mt=s.get(F);mt&&b.set(F,mt)}let R=new Set;for(let F of b.keys()){let mt=a?.files[F]!==void 0,Vc=i.has(F);!mt&&!Vc&&R.add(F)}let k=await this.uploadFilesAtomic(b,R);if(k.error){this.hasError=!0,console.error(k.error.message);for(let F of k.error.perFile)console.error(` ${F.path}: ${F.title}`)}else this.pushedFiles.push(...k.succeeded)}if(p.length>0){console.log(`
94
+ Pulling ${d.length} file(s)...`);let b=await Promise.all(d.map(R=>this.remoteLimit(async()=>{try{let k=Zn.join(this.options.localDir,R);return await this.downloadFile(R,k),R}catch(k){return this.hasError=!0,console.error(`Error downloading ${R}:`,k),null}})));this.pulledFiles.push(...b.filter(R=>R!==null))}if(m.length>0){console.log(`
95
+ Pushing ${m.length} file(s)...`);let b=new Map;for(let F of m){let ft=s.get(F);ft&&b.set(F,ft)}let R=new Set;for(let F of b.keys()){let ft=a?.files[F]!==void 0,Vc=i.has(F);!ft&&!Vc&&R.add(F)}let k=await this.uploadFilesAtomic(b,R);if(k.error){this.hasError=!0,console.error(k.error.message);for(let F of k.error.perFile)console.error(` ${F.path}: ${F.title}`)}else this.pushedFiles.push(...k.succeeded)}if(p.length>0){console.log(`
96
96
  Deleting ${p.length} remote file(s)...`);let b=await Promise.all(p.map(R=>this.remoteLimit(async()=>{try{return await this.deleteFile(R),R}catch(k){return this.hasError=!0,console.error(`Error deleting remote ${R}:`,k),null}})));this.remoteDeletedFiles.push(...b.filter(R=>R!==null))}if(w.length>0){console.log(`
97
- Deleting ${w.length} local file(s)...`);let b=await Promise.all(w.map(async R=>{try{let k=s.get(R);return k?(await this.deleteLocalFile(k),R):null}catch(k){return this.hasError=!0,console.error(`Error deleting local ${R}:`,k),null}}));this.localDeletedFiles.push(...b.filter(R=>R!==null))}if(!this.options.dryRun&&!this.hasError){let b=new Map;if(a)for(let[k,F]of Object.entries(a.files))b.set(k,F);for(let[k,F]of l)b.set(k,F);for(let k of this.pushedFiles){let F=s.get(k);F&&b.set(k,await oe(F))}for(let k of this.pulledFiles){let F=Qn.join(this.options.localDir,k);b.set(k,await oe(F))}for(let k of this.remoteDeletedFiles)b.delete(k);for(let k of this.localDeletedFiles)b.delete(k);let R=i;if(this.pushedFiles.length>0||this.remoteDeletedFiles.length>0)try{R=await this.getRemoteMtimes()}catch{console.warn("Could not refresh remote mtimes after sync")}await this.writeManifest(b,R)}if(!this.options.dryRun){let b=[...this.pushedFiles.map(R=>({file:R,status:"modified"})),...this.pulledFiles.map(R=>({file:R,status:"modified"})),...this.remoteDeletedFiles.map(R=>({file:R,status:"deleted"})),...this.localDeletedFiles.map(R=>({file:R,status:"deleted"}))];if(b.length>0){let k=await new U(this.options.localDir).createCheckpoint("local",b);if(k){let F=k.isMajor?"[MAJOR]":"[minor]";console.log(`
97
+ Deleting ${w.length} local file(s)...`);let b=await Promise.all(w.map(async R=>{try{let k=s.get(R);return k?(await this.deleteLocalFile(k),R):null}catch(k){return this.hasError=!0,console.error(`Error deleting local ${R}:`,k),null}}));this.localDeletedFiles.push(...b.filter(R=>R!==null))}if(!this.options.dryRun&&!this.hasError){let b=new Map;if(a)for(let[k,F]of Object.entries(a.files))b.set(k,F);for(let[k,F]of l)b.set(k,F);for(let k of this.pushedFiles){let F=s.get(k);F&&b.set(k,await Z(F))}for(let k of this.pulledFiles){let F=Zn.join(this.options.localDir,k);b.set(k,await Z(F))}for(let k of this.remoteDeletedFiles)b.delete(k);for(let k of this.localDeletedFiles)b.delete(k);let R=i;if(this.pushedFiles.length>0||this.remoteDeletedFiles.length>0)try{R=await this.getRemoteMtimes()}catch{console.warn("Could not refresh remote mtimes after sync")}await this.writeManifest(b,R)}if(!this.options.dryRun){let b=[...this.pushedFiles.map(R=>({file:R,status:"modified"})),...this.pulledFiles.map(R=>({file:R,status:"modified"})),...this.remoteDeletedFiles.map(R=>({file:R,status:"deleted"})),...this.localDeletedFiles.map(R=>({file:R,status:"deleted"}))];if(b.length>0){let k=await new U(this.options.localDir).createCheckpoint("local",b);if(k){let F=k.isMajor?"[MAJOR]":"[minor]";console.log(`
98
98
  Checkpoint created: ${k.shortHash} ${F} ${k.message}`)}}}console.log(`
99
- Sync completed`)}async writeManifest(t,n){let i={realmUrl:this.normalizedRealmUrl,files:{},remoteMtimes:{}};for(let[o,s]of t){i.files[o]=s;let a=n.get(o);a!==void 0&&a!==0&&(i.remoteMtimes[o]=a)}i.remoteMtimes&&Object.keys(i.remoteMtimes).length===0&&delete i.remoteMtimes,await Re(this.options.localDir,i)}};function fc(r){return r.command("sync").description("Bidirectional sync between a local directory and a Boxel realm").argument("<local-dir>","The local directory to sync").argument("<realm-url>","The URL of the target realm (e.g., https://app.boxel.ai/demo/)").option("--prefer-local","Resolve conflicts by keeping local version").option("--prefer-remote","Resolve conflicts by keeping remote version").option("--prefer-newest","Resolve conflicts by keeping newest version").option("--delete","Sync deletions both ways").option("--dry-run","Preview without making changes").option("--realm-secret-seed","Administrative auth: prompt for a realm secret seed and mint a JWT locally instead of using a Matrix profile (env: BOXEL_REALM_SECRET_SEED)").action(async(t,n,i)=>{let o=await me(i.realmSecretSeed===!0),s=await Ew(t,n,{preferLocal:i.preferLocal,preferRemote:i.preferRemote,preferNewest:i.preferNewest,delete:i.delete,dryRun:i.dryRun,realmSecretSeed:o}),a=Array.isArray(s.pushed)&&s.pushed.length>0||Array.isArray(s.pulled)&&s.pulled.length>0||Array.isArray(s.remoteDeleted)&&s.remoteDeleted.length>0||Array.isArray(s.localDeleted)&&s.localDeleted.length>0;s.error&&(console.error(`Error: ${s.error}`),process.exit(a?2:1)),console.log("Sync completed successfully")})}async function Ew(r,e,t){let n;if(t.authenticator)n=t.authenticator;else{let s=de({realmUrl:e,realmSecretSeed:t.realmSecretSeed,profileManager:t.profileManager});if(!s.ok)return Kn({error:s.error});n=s.authenticator}if([t.preferLocal,t.preferRemote,t.preferNewest].filter(Boolean).length>1)return Kn({error:"Only one conflict strategy can be specified (--prefer-local, --prefer-remote, or --prefer-newest)."});if(!await Ge(r))return Kn({error:`Local directory does not exist: ${r}`});let o;try{o=new Zn({realmUrl:e,localDir:r,preferLocal:t.preferLocal,preferRemote:t.preferRemote,preferNewest:t.preferNewest,deleteSync:t.delete,dryRun:t.dryRun,waitForIndex:t.waitForIndex},n),await o.sync()}catch(s){return{pushed:o?.pushedFiles.slice().sort()??[],pulled:o?.pulledFiles.slice().sort()??[],remoteDeleted:o?.remoteDeletedFiles.slice().sort()??[],localDeleted:o?.localDeletedFiles.slice().sort()??[],skippedConflicts:o?.skippedConflicts.slice().sort()??[],hasError:!0,error:`Sync failed: ${s instanceof Error?s.message:String(s)}`}}return{pushed:o.pushedFiles.slice().sort(),pulled:o.pulledFiles.slice().sort(),remoteDeleted:o.remoteDeletedFiles.slice().sort(),localDeleted:o.localDeletedFiles.slice().sort(),skippedConflicts:o.skippedConflicts.slice().sort(),hasError:o.hasError,error:o.hasError?$w(o):void 0}}function $w(r){return`Sync completed with errors. ${[`${r.pushedFiles.length} pushed`,`${r.pulledFiles.length} pulled`,`${r.remoteDeletedFiles.length} remote deleted`,`${r.localDeletedFiles.length} local deleted`,`${r.skippedConflicts.length} conflicts skipped`].join(", ")}.`}function Kn(r){return{pushed:[],pulled:[],remoteDeleted:[],localDeleted:[],skippedConflicts:[],hasError:!0,...r}}var mc=O(yt());function bw(r){let e=Number.parseInt(r,10);if(!Number.isFinite(e)||e<0||String(e)!==r.trim())throw new mc.InvalidArgumentError("--timeout must be a non-negative integer (milliseconds).");return e}async function Rw(r,e={}){let t=e.timeoutMs??3e4;if(!Number.isFinite(t)||t<0)return{ready:!1,error:`Invalid timeoutMs: must be a finite, non-negative number (got ${e.timeoutMs}).`};let n=e.profileManager??A();if(!n.getActiveProfile())return{ready:!1,error:M};let o=`${P(r)}_readiness-check`,s=Date.now();for(;Date.now()-s<t;){try{if((await n.authedRealmFetch(o,{method:"GET",headers:{Accept:"application/vnd.api+json"}})).ok)return{ready:!0}}catch{}let a=t-(Date.now()-s);if(a<=0)break;await new Promise(l=>setTimeout(l,Math.min(1e3,a)))}return{ready:!1,error:`Realm not ready after ${t}ms: ${o}`}}function dc(r){r.command("wait-for-ready").description("Poll a realm readiness-check endpoint until it responds OK or the timeout is reached").requiredOption("--realm <realm-url>","The realm URL to check").option("--timeout <ms>","Timeout in milliseconds (default: 30000)",bw).action(async e=>{let t;try{t=await Rw(e.realm,{timeoutMs:e.timeout})}catch(n){console.error(`${h}Error:${f} ${n instanceof Error?n.message:String(n)}`),process.exit(1)}t.ready?console.log(`${S}Realm is ready.${f}`):(console.error(`${h}Error:${f} ${t.error??"Realm not ready"}`),process.exit(1))})}var ai=O(yt()),Sc=O(require("fs/promises")),lt=O(require("path"));var Se=O(require("fs/promises")),pc=O(require("path")),Sw=".boxel-watch.lock";function ei(r){return pc.join(r,Sw)}function ti(r){try{return process.kill(r,0),!0}catch(e){return e?.code==="EPERM"}}async function vw(r){try{let e=await Se.readFile(ei(r),"utf8"),t=JSON.parse(e);return typeof t.pid!="number"||typeof t.startedAt!="string"||typeof t.realmUrl!="string"?null:t}catch{return null}}async function hc(r,e){await Se.mkdir(r,{recursive:!0});let t=await vw(r),n=!1;if(t&&ti(t.pid))return{ok:!1,existing:t};t&&(n=!0);let i={pid:process.pid,startedAt:new Date().toISOString(),realmUrl:e};return await Se.writeFile(ei(r),JSON.stringify(i,null,2)+`
100
- `),{ok:!0,staleOverwrote:n}}async function fr(r){try{await Se.unlink(ei(r))}catch(e){if(e?.code!=="ENOENT")throw e}}var ve=O(require("fs/promises")),gc=O(require("os")),ri=O(require("path"));function yc(){return ri.join(gc.homedir(),".boxel-cli")}function wc(){return ri.join(yc(),"watch-processes.json")}async function Ec(){try{let r=await ve.readFile(wc(),"utf8"),e=JSON.parse(r);return Array.isArray(e?.processes)?{processes:e.processes.filter(n=>typeof n?.pid=="number"&&typeof n?.workspace=="string"&&typeof n?.startedAt=="string")}:{processes:[]}}catch{return{processes:[]}}}async function ni(r){await ve.mkdir(yc(),{recursive:!0});let e=wc(),t=`${e}.${process.pid}.tmp`;await ve.writeFile(t,JSON.stringify(r,null,2)+`
101
- `),await ve.rename(t,e)}async function $c(){let r=await Ec(),e=r.processes.filter(t=>ti(t.pid));return e.length!==r.processes.length&&await ni({processes:e}),{processes:e}}async function bc(r){let t=(await $c()).processes.filter(n=>n.pid!==process.pid);t.push({pid:process.pid,workspace:r,startedAt:new Date().toISOString()}),await ni({processes:t})}async function Rc(){let r=await Ec(),e=r.processes.filter(t=>t.pid!==process.pid);e.length!==r.processes.length&&await ni({processes:e})}async function ii(){return(await $c()).processes}var oi=class extends ie{name;debounceMs;checkpointManager;lastKnownMtimes=new Map;pendingChanges=new Map;debounceTimer=null;isShutdown=!1;constructor(e,t,n){super({realmUrl:e.realmUrl,localDir:e.localDir},t),this.debounceMs=n.debounceMs,this.checkpointManager=new U(e.localDir),this.name=Ow(this.normalizedRealmUrl)}async sync(){await this.poll(),await this.flushPending()}async getRemoteMtimes(){let e=`${this.normalizedRealmUrl}_mtimes`,t=await this.authenticator.authedRealmFetch(e,{headers:{Accept:"application/vnd.api+json"}});if(!t.ok)throw new Error(`_mtimes fetch failed for ${this.normalizedRealmUrl}: ${t.status} ${t.statusText}`);let n=await t.json(),i=new Map;for(let[o,s]of Object.entries(n.data?.attributes?.mtimes??{}))i.set(o.replace(this.normalizedRealmUrl,""),s);return i}get localDir(){return this.options.localDir}get realmUrl(){return this.normalizedRealmUrl}get pendingCount(){return this.pendingChanges.size}async initialize(){await this.getRemoteMtimes(),await this.checkpointManager.isInitialized()||await this.checkpointManager.init();let e=await ye(this.options.localDir);if(e&&e.realmUrl===this.normalizedRealmUrl&&e.remoteMtimes)for(let[t,n]of Object.entries(e.remoteMtimes))this.lastKnownMtimes.set(t,n)}async poll(){let e=await this.getRemoteMtimes(),t=!1;for(let[n,i]of e){if(D(n))continue;let o=this.lastKnownMtimes.get(n);o===void 0?this.recordPending(n,{status:"added",mtime:i})&&(t=!0):i>o&&this.recordPending(n,{status:"modified",mtime:i})&&(t=!0)}for(let n of this.lastKnownMtimes.keys())D(n)||e.has(n)||this.pendingChanges.get(n)?.status!=="deleted"&&(this.pendingChanges.set(n,{status:"deleted",mtime:0}),t=!0);return t}async flushPending(){if(this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.pendingChanges.size===0)return{pulled:[],deleted:[],checkpoint:null};let e=new Map(this.pendingChanges);this.pendingChanges.clear();let t=[],n=[],i=[];for(let[s,a]of e)if(a.status==="deleted"){let l=lt.join(this.options.localDir,s);try{await Sc.unlink(l)}catch(u){if(u.code!=="ENOENT")throw u}n.push(s),i.push({file:s,status:"deleted"})}else{let l=lt.join(this.options.localDir,s);await this.downloadFile(s,l),t.push(s),i.push({file:s,status:a.status})}for(let[s,a]of e)a.status==="deleted"?this.lastKnownMtimes.delete(s):this.lastKnownMtimes.set(s,a.mtime);await this.persistManifest(t,n);let o=await this.checkpointManager.createCheckpoint("remote",i);return{pulled:t,deleted:n,checkpoint:o}}scheduleFlush(e){this.isShutdown||(this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(async()=>{this.debounceTimer=null;try{let t=await this.flushPending();e?.(t)}catch(t){console.error(`${h}[${this.name}] Error applying changes:${f}`,t)}},this.debounceMs))}shutdown(){this.isShutdown=!0,this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}recordPending(e,t){let n=this.pendingChanges.get(e);return n&&n.mtime===t.mtime?!1:(this.pendingChanges.set(e,t),!0)}async persistManifest(e,t){let n=await ye(this.options.localDir),i=n?.files?{...n.files}:{};for(let a of t)delete i[a];for(let a of e){let l=lt.join(this.options.localDir,a);try{i[a]=await oe(l)}catch(u){if(u.code!=="ENOENT")throw u}}let o={};for(let[a,l]of this.lastKnownMtimes)l!==0&&(o[a]=l);let s={realmUrl:this.normalizedRealmUrl,files:i};Object.keys(o).length>0&&(s.remoteMtimes=o),await Re(this.options.localDir,s)}};async function xw(r,e={}){if(r.length===0)return{watchers:[],error:"No realms provided to watch."};let t=e.intervalMs??3e4,n=e.debounceMs??5e3,i=e.quiet??!1;if(!Number.isFinite(t)||t<=0)return{watchers:[],error:"`intervalMs` must be a positive number."};if(!Number.isFinite(n)||n<0)return{watchers:[],error:"`debounceMs` must be a non-negative number."};let o;if(e.authenticator)o=e.authenticator;else{let d=de({realmUrl:r[0].realmUrl,realmSecretSeed:e.realmSecretSeed,profileManager:e.profileManager});if(!d.ok)return{watchers:[],error:d.error};o=d.authenticator}let s=[];for(let d of r){let p=await hc(d.localDir,d.realmUrl);if(!p.ok){for(let w of s)await fr(w);return{watchers:[],error:_w(d.localDir,p.existing)}}p.staleOverwrote&&!i&&console.log(`${y}[${si()}] overwrote stale lock at ${d.localDir}${f}`),s.push(d.localDir)}let a=[];for(let d of r){let p=new oi(d,o,{debounceMs:n});try{await p.initialize()}catch(w){for(let x of a)x.shutdown();for(let x of s)await fr(x);return{watchers:[],error:`Failed to initialize watch on ${d.realmUrl}: ${w instanceof Error?w.message:String(w)}`}}a.push(p)}if(!i){console.log(`${_}\u21C5 Watching ${a.length} realm${a.length>1?"s":""}:${f}`);for(let d of a)console.log(` ${d.name} ${y}\u2192${f} ${d.localDir}`);console.log(` ${y}Interval: ${t/1e3}s, Debounce: ${n/1e3}s${f}`),console.log(` ${y}Press Ctrl+C to stop${f}
102
- `)}let l=async()=>{await Promise.all(a.map(async d=>{try{await d.poll()&&(i||console.log(`${y}[${si()}]${f} [${d.name}] ${C}\u26A1 ${d.pendingCount} change(s) detected${f}`),d.scheduleFlush(w=>{i||kw(d.name,w)}))}catch(p){console.error(`${h}[${d.name}] poll error:${f}`,p instanceof Error?p.message:p)}}))},u=!1,c=null,m=()=>{u||(c=setTimeout(async()=>{c=null,!u&&(await l(),m())},t))};try{await bc(r.map(d=>d.localDir).join(", "))}catch{}return await l(),m(),await new Promise(d=>{let p=null,w=null,x=async()=>{if(!u){u=!0,c!==null&&(clearTimeout(c),c=null);for(let Q of a)Q.shutdown();p&&process.off("SIGINT",p),w&&process.off("SIGTERM",w);for(let Q of s)try{await fr(Q)}catch{}try{await Rc()}catch{}d()}};if(e.signal){if(e.signal.aborted){x();return}e.signal.addEventListener("abort",()=>void x(),{once:!0})}else p=()=>{i||console.log(`
103
- ${_}\u21C5 Watch stopped${f}`),x()},w=p,process.on("SIGINT",p),process.on("SIGTERM",w)}),{watchers:a}}function _w(r,e){return`A boxel realm watch process is already active for ${r} (pid ${e.pid}, started ${e.startedAt}). Stop it before starting a new one, or remove ${lt.join(r,".boxel-watch.lock")} if it's stale.`}function kw(r,e){let t=e.pulled.length+e.deleted.length;if(t!==0&&(console.log(`${y}[${si()}]${f} [${r}] ${S}applied ${t} change(s)${f} (${e.pulled.length} pulled, ${e.deleted.length} deleted)`),e.checkpoint)){let n=e.checkpoint.isMajor?"[MAJOR]":"[minor]";console.log(` ${y}Checkpoint:${f} ${e.checkpoint.shortHash} ${n} ${e.checkpoint.message}`)}}function Ow(r){return r.replace(/\/$/,"").split("/").slice(-2).join("/")}function si(){return new Date().toLocaleTimeString()}function Cw(r){return e=>{let t=Number.parseFloat(e);if(!Number.isFinite(t)||t<=0)throw new ai.InvalidArgumentError(`${r} must be a positive number.`);return t}}function Aw(r){return e=>{let t=Number.parseFloat(e);if(!Number.isFinite(t)||t<0)throw new ai.InvalidArgumentError(`${r} must be a non-negative number.`);return t}}function vc(r){r.command("start").description("Start watching a Boxel realm for server-side changes and pull them into a local directory").argument("<realm-url>","The URL of the realm to watch (e.g., https://app.boxel.ai/demo/)").argument("<local-dir>","The local directory to write changes into").option("-i, --interval <seconds>","Polling interval in seconds",Cw("--interval"),30).option("-d, --debounce <seconds>","Seconds to wait after a burst of changes before applying them",Aw("--debounce"),5).option("--realm-secret-seed","Administrative auth: prompt for a realm secret seed and mint a JWT locally instead of using a Matrix profile (env: BOXEL_REALM_SECRET_SEED)").action(async(e,t,n)=>{let i=await me(n.realmSecretSeed===!0),o=await xw([{realmUrl:e,localDir:t}],{intervalMs:n.interval*1e3,debounceMs:n.debounce*1e3,realmSecretSeed:i});o.error&&(console.error(`${h}Error:${f} ${o.error}`),process.exit(1))})}var li=require("child_process");var Pw=200;function Tw(r){return new Promise(e=>setTimeout(e,r))}function xc(r){try{if(process.platform==="win32")try{process.kill(r)}catch{(0,li.execSync)(`taskkill /PID ${r} /F`,{stdio:"ignore"})}else process.kill(r,"SIGINT");return{ok:!0,alreadyGone:!1}}catch(e){return e?.code==="ESRCH"?{ok:!0,alreadyGone:!0}:{ok:!1,alreadyGone:!1}}}function Lw(){if(process.platform==="win32")return[];let r;try{r=(0,li.execSync)('ps aux | grep -E "(tsx[[:space:]].*src/index\\.ts[[:space:]]+realm[[:space:]]+watch[[:space:]]+start|[[:space:]]boxel[[:space:]]+realm[[:space:]]+watch[[:space:]]+start|node[[:space:]].*boxel[[:space:]]+realm[[:space:]]+watch[[:space:]]+start)" | grep -v grep | grep -v "[[:space:]]stop"',{encoding:"utf8"}).trim()}catch{return[]}if(!r)return[];let e=[],t=new Set;for(let n of r.split(`
104
- `)){if(!n)continue;let i=n.trim().split(/\s+/),o=Number.parseInt(i[1]??"",10);if(!Number.isFinite(o)||t.has(o))continue;t.add(o);let s=".",a=n.match(/\bstart\s+\S+\s+(\S+)/);a&&a[1]&&!a[1].startsWith("-")&&(s=a[1]),e.push({pid:o,workspace:s})}return e}async function Iw(){let r=[],e=[],t=new Set,n=await ii();for(let i of n){if(i.pid===process.pid)continue;t.add(i.pid);let o=xc(i.pid),s={pid:i.pid,workspace:i.workspace};o.ok?r.push(s):e.push(s)}for(let i of Lw()){if(i.pid===process.pid||t.has(i.pid))continue;t.add(i.pid);let o=xc(i.pid),s={pid:i.pid,workspace:i.workspace};o.ok?r.push(s):e.push(s)}return r.length>0&&(await Tw(Pw),await ii()),{stopped:r,failed:e}}function Mw(r){if(r.stopped.length===0&&r.failed.length===0){console.log("No running watch processes found.");return}for(let e of r.stopped)console.log(` ${y}\u21C5${f} Stopped: boxel realm watch ${e.workspace} (PID ${e.pid})`);for(let e of r.failed)console.log(` ${h}\xD7${f} Failed to stop: boxel realm watch ${e.workspace} (PID ${e.pid})`);if(r.stopped.length>0){let e=r.stopped.length>1?"es":"";console.log(`
105
- ${S}\u2713 Stopped ${r.stopped.length} process${e}${f}`)}}function _c(r){r.command("stop").description("Stop all running boxel realm watch processes").action(async()=>{let e=await Iw();Mw(e)})}function kc(r){let e=r.command("watch").description("Watch a Boxel realm; subcommands manage watch processes");vc(e),_c(e)}function Oc(r){let e=r.command("realm").description("Manage realms on the realm server");Ol(e),Tl(e),zl(e),Jl(e),Ql(e),rc(e),ic(e),sc(e);let t=fc(e);uc(t),dc(e),kc(e)}async function Nw(r,e,t){let n=t?.profileManager??A();if(!n.getActiveProfile())return{ok:!1,error:M};if(D(e))return{ok:!1,error:`Cannot delete protected file: ${e}`};let o=new URL(e,P(r)).href,s;try{s=await n.authedRealmFetch(o,{method:"DELETE",headers:{Accept:"application/vnd.card+source"}})}catch(a){return{ok:!1,error:a instanceof Error?a.message:String(a)}}if(!s.ok){let a=await s.text().catch(()=>"(no body)");return{ok:!1,error:`HTTP ${s.status}: ${a.slice(0,300)}`}}return{ok:!0}}function Cc(r){r.command("delete").description("Delete a file from a realm").argument("<path>","Realm-relative file path to delete").requiredOption("--realm <realm-url>","The realm URL to delete from").option("--json","Output raw JSON response").action(async(e,t)=>{let n;try{n=await Nw(t.realm,e)}catch(i){console.error(`${h}Error:${f} ${i instanceof Error?i.message:String(i)}`),process.exit(1)}t.json?N.output(JSON.stringify(n,null,2)):n.ok?console.log(`${y}Deleted:${f} ${e}`):console.error(`${h}Error:${f} ${n.error}`),n.ok||process.exit(1)})}async function ci(r,e){let t=e?.profileManager??A();if(!t.getActiveProfile())return{filenames:[],error:M};let i=P(r),o=`${i}_mtimes`;try{let s=await t.authedRealmFetch(o,{method:"GET",headers:{Accept:"application/vnd.api+json"}});if(!s.ok){let c=await s.text().catch(()=>"(no body)");return{filenames:[],error:`_mtimes returned HTTP ${s.status}: ${c.slice(0,300)}`}}let a=await s.json(),l=a?.data?.attributes?.mtimes??a,u=[];for(let c of Object.keys(l)){if(!c.startsWith(i))continue;let m=c.slice(i.length);!m||m.endsWith("/")||u.push(m)}return{filenames:u.sort()}}catch(s){return{filenames:[],error:s instanceof Error?s.message:String(s)}}}function Ac(r){r.command("list").alias("ls").description("List all files in a realm").requiredOption("--realm <realm-url>","The realm URL to list files from").option("--json","Output raw JSON response").action(async e=>{let t;try{t=await ci(e.realm)}catch(n){console.error(`${h}Error:${f} ${n instanceof Error?n.message:String(n)}`),process.exit(1)}if(e.json)N.output(JSON.stringify(t,null,2)),t.error&&process.exit(1);else if(t.error)console.error(`${h}Error:${f} ${t.error}`),process.exit(1);else{for(let n of t.filenames)console.log(`${y}${n}${f}`);console.log(`
106
- ${y}${t.filenames.length} file(s)${f}`)}})}var mr=require("fs");var Pc=require("fs");async function ut(r,e,t,n){let i=n?.profileManager??A();if(!i.getActiveProfile())return{ok:!1,error:M};let s=new URL(e,P(r)).href;try{let a=await i.authedRealmFetch(s,{method:"POST",headers:{Accept:"application/vnd.card+source","Content-Type":"application/vnd.card+source"},body:t});if(!a.ok){let l=await a.text().catch(()=>"(no body)");return{ok:!1,error:`HTTP ${a.status}: ${l.slice(0,300)}`}}return{ok:!0}}catch(a){return{ok:!1,error:a instanceof Error?a.message:String(a)}}}function ct(r){process.stderr.write(r+`
107
- `)}async function Dw(){let r=[];for await(let e of process.stdin)r.push(e);return Buffer.concat(r).toString("utf-8")}function Tc(r){r.command("write").description("Write a file to a realm (reads content from STDIN or --file)").argument("<path>","Realm-relative file path (e.g., hello.gts, Cards/my-card.json)").requiredOption("--realm <realm-url>","The realm URL to write to").option("--file <filepath>","Read content from a local file instead of STDIN").option("--json","Output raw JSON response").action(async(e,t)=>{let n;if(t.file)try{n=(0,Pc.readFileSync)(t.file,"utf-8")}catch(o){ct(`${h}Error:${f} Could not read file: ${o instanceof Error?o.message:String(o)}`),process.exit(1)}else process.stdin.isTTY&&ct(`${y}Reading from STDIN. Type or paste content, then press Enter followed by Ctrl+D to finish.${f}`),n=await Dw(),ct(`${y}Received ${n.length} bytes. Writing to realm...${f}`);let i;try{i=await ut(t.realm,e,n)}catch(o){ct(`${h}Error:${f} ${o instanceof Error?o.message:String(o)}`),process.exit(1)}t.json?N.output(JSON.stringify(i,null,2)):i.ok?console.log(`${S}Written:${f} ${e} ${y}\u2192${f} ${t.realm}`):ct(`${h}Error:${f} ${i.error}`),i.ok||process.exit(1)})}async function Fw(r,e,t,n){let i=n?.profileManager??A();if(!i.getActiveProfile())return{ok:!1,error:M};let s=`${P(r)}_lint`;try{let a=await i.authedRealmFetch(s,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/vnd.card+source","X-Filename":t,"X-HTTP-Method-Override":"QUERY"},body:e});if(!a.ok){let u=await a.text().catch(()=>"(no body)");return{ok:!1,error:`HTTP ${a.status}: ${u.slice(0,300)}`}}let l=await a.json();return{ok:!0,fixed:l.fixed,output:l.output,messages:l.messages}}catch(a){return{ok:!1,error:a instanceof Error?a.message:String(a)}}}function Lc(r){r.command("lint").description("Lint a file in a realm using the realm lint endpoint").argument("<path>","Realm-relative file path to lint (e.g., my-card.gts)").requiredOption("--realm <realm-url>","The realm URL to lint against").option("--file <local-filepath>","Read source from a local file instead of fetching from the realm").option("--json","Output raw JSON response").option("--fix","Write auto-fixed output back to the source").action(async(e,t)=>{let n=A();n.getActiveProfile()||(console.error(`${h}Error:${f} ${M}`),process.exit(1));let o;if(t.file)try{o=(0,mr.readFileSync)(t.file,"utf-8")}catch(c){console.error(`${h}Error:${f} Could not read local file: ${c instanceof Error?c.message:String(c)}`),process.exit(1)}else{let c=new URL(e,P(t.realm)).href;try{let m=await n.authedRealmFetch(c,{method:"GET",headers:{Accept:"application/vnd.card+source"}});if(!m.ok){let d=await m.text().catch(()=>"(no body)");console.error(`${h}Error:${f} Could not read file from realm: HTTP ${m.status}: ${d.slice(0,300)}`),process.exit(1)}o=await m.text()}catch(m){console.error(`${h}Error:${f} ${m instanceof Error?m.message:String(m)}`),process.exit(1)}}let s;try{s=await Fw(t.realm,o,e,{profileManager:n})}catch(c){console.error(`${h}Error:${f} ${c instanceof Error?c.message:String(c)}`),process.exit(1)}if(t.json){N.output(JSON.stringify(s,null,2)),s.ok||process.exit(1);return}if(s.ok||(console.error(`${h}Error:${f} ${s.error}`),process.exit(1)),t.fix&&s.fixed&&s.output)if(t.file)(0,mr.writeFileSync)(t.file,s.output,"utf-8"),console.log(`${S}Fixed:${f} ${t.file}`);else{let c=await ut(t.realm,e,s.output,{profileManager:n});c.ok||(console.error(`${h}Error:${f} Could not write fixed file: ${c.error}`),process.exit(1)),console.log(`${S}Fixed:${f} ${e} ${y}\u2192${f} ${t.realm}`)}let a=s.messages??[],l=a.filter(c=>c.severity===2),u=a.filter(c=>c.severity===1);if(a.length===0){console.log(`${y}No lint issues found.${f}`);return}for(let c of a){let m=c.severity===2?h:C,d=c.severity===2?"error":"warning",p=c.ruleId?` (${c.ruleId})`:"";console.log(`${m}${d}${f} ${c.line}:${c.column} ${c.message}${y}${p}${f}`)}console.log(`
108
- ${y}${l.length} error(s), ${u.length} warning(s)${f}`),l.length>0&&process.exit(1)})}async function ui(r,e,t){let n=t?.profileManager??A();if(!n.getActiveProfile())return{ok:!1,error:M};let o=new URL(e,P(r)).href,s;try{s=await n.authedRealmFetch(o,{method:"GET",headers:{Accept:"application/vnd.card+source"}})}catch(l){return{ok:!1,error:l instanceof Error?l.message:String(l)}}if(!s.ok){let l=await s.text().catch(()=>"(no body)");return{ok:!1,status:s.status,error:`HTTP ${s.status}: ${l.slice(0,300)}`}}let a=await s.text();return{ok:!0,status:s.status,content:a}}function Ic(r){r.command("read").description("Read a file from a realm").argument("<path>","Realm-relative file path (e.g., hello-world.json, Cards/my-card.gts)").requiredOption("--realm <realm-url>","The realm URL to read from").option("--json","Output raw JSON response").action(async(e,t)=>{let n;try{n=await ui(t.realm,e)}catch(i){console.error(`${h}Error:${f} ${i instanceof Error?i.message:String(i)}`),process.exit(1)}t.json?N.output(JSON.stringify(n,null,2)):n.ok?N.output(n.content??""):(console.error(`${y}Status:${f} ${n.status??"(no status)"}`),console.error(`${h}Error:${f} ${n.error}`)),n.ok||process.exit(1)})}var fi="// touched for re-index";async function Uw(r,e,t){let n=t?.profileManager??A();if(!n.getActiveProfile())return{ok:!1,touched:[],skipped:[],error:M};let o;if(t?.all){if(e.length>0)return{ok:!1,touched:[],skipped:[],error:"Cannot pass file paths together with --all"};let l=await ci(r,{profileManager:n});if(l.error)return{ok:!1,touched:[],skipped:[],error:l.error};o=l.filenames.filter(u=>(u.endsWith(".json")||u.endsWith(".gts"))&&!D(u))}else{if(e.length===0)return{ok:!1,touched:[],skipped:[],error:"No file paths provided. Pass paths or use --all."};o=e}let s=[],a=[];for(let l of o){if(!l.endsWith(".json")&&!l.endsWith(".gts")){a.push({path:l,reason:"unsupported extension"});continue}if(D(l)){a.push({path:l,reason:"protected file"});continue}let u=await ui(r,l,{profileManager:n});if(!u.ok||u.content==null){a.push({path:l,reason:u.error??"read failed"});continue}if(t?.dryRun){s.push(l);continue}let c=l.endsWith(".json")?jw(u.content):Gw(u.content),m=await ut(r,l,c,{profileManager:n});if(!m.ok){a.push({path:l,reason:m.error??"write failed"});continue}s.push(l)}return{ok:a.length===0,touched:s,skipped:a}}function jw(r){try{let e=JSON.parse(r);if(e?.data)return e.data.meta={...e.data.meta??{},_touched:Date.now()},JSON.stringify(e,null,2)+`
99
+ Sync completed`)}async writeManifest(t,n){let i={realmUrl:this.normalizedRealmUrl,files:{},remoteMtimes:{}};for(let[o,s]of t){i.files[o]=s;let a=n.get(o);a!==void 0&&a!==0&&(i.remoteMtimes[o]=a)}i.remoteMtimes&&Object.keys(i.remoteMtimes).length===0&&delete i.remoteMtimes,await Se(this.options.localDir,i)}};function fc(r){return r.command("sync").description("Bidirectional sync between a local directory and a Boxel realm").argument("<local-dir>","The local directory to sync").argument("<realm-url>","The URL of the target realm (e.g., https://app.boxel.ai/demo/)").option("--prefer-local","Resolve conflicts by keeping local version").option("--prefer-remote","Resolve conflicts by keeping remote version").option("--prefer-newest","Resolve conflicts by keeping newest version").option("--delete","Sync deletions both ways").option("--dry-run","Preview without making changes").option("--realm-secret-seed","Administrative auth: prompt for a realm secret seed and mint a JWT locally instead of using a Matrix profile (env: BOXEL_REALM_SECRET_SEED)").action(async(t,n,i)=>{let o=await me(i.realmSecretSeed===!0),s=await Ew(t,n,{preferLocal:i.preferLocal,preferRemote:i.preferRemote,preferNewest:i.preferNewest,delete:i.delete,dryRun:i.dryRun,realmSecretSeed:o}),a=Array.isArray(s.pushed)&&s.pushed.length>0||Array.isArray(s.pulled)&&s.pulled.length>0||Array.isArray(s.remoteDeleted)&&s.remoteDeleted.length>0||Array.isArray(s.localDeleted)&&s.localDeleted.length>0;s.error&&(console.error(`Error: ${s.error}`),process.exit(a?2:1)),console.log("Sync completed successfully")})}async function Ew(r,e,t){let n;if(t.authenticator)n=t.authenticator;else{let s=de({realmUrl:e,realmSecretSeed:t.realmSecretSeed,profileManager:t.profileManager});if(!s.ok)return Qn({error:s.error});n=s.authenticator}if([t.preferLocal,t.preferRemote,t.preferNewest].filter(Boolean).length>1)return Qn({error:"Only one conflict strategy can be specified (--prefer-local, --prefer-remote, or --prefer-newest)."});if(!await Ve(r))return Qn({error:`Local directory does not exist: ${r}`});let o;try{o=new ei({realmUrl:e,localDir:r,preferLocal:t.preferLocal,preferRemote:t.preferRemote,preferNewest:t.preferNewest,deleteSync:t.delete,dryRun:t.dryRun,waitForIndex:t.waitForIndex},n),await o.sync()}catch(s){return{pushed:o?.pushedFiles.slice().sort()??[],pulled:o?.pulledFiles.slice().sort()??[],remoteDeleted:o?.remoteDeletedFiles.slice().sort()??[],localDeleted:o?.localDeletedFiles.slice().sort()??[],skippedConflicts:o?.skippedConflicts.slice().sort()??[],hasError:!0,error:`Sync failed: ${s instanceof Error?s.message:String(s)}`}}return{pushed:o.pushedFiles.slice().sort(),pulled:o.pulledFiles.slice().sort(),remoteDeleted:o.remoteDeletedFiles.slice().sort(),localDeleted:o.localDeletedFiles.slice().sort(),skippedConflicts:o.skippedConflicts.slice().sort(),hasError:o.hasError,error:o.hasError?$w(o):void 0}}function $w(r){return`Sync completed with errors. ${[`${r.pushedFiles.length} pushed`,`${r.pulledFiles.length} pulled`,`${r.remoteDeletedFiles.length} remote deleted`,`${r.localDeletedFiles.length} local deleted`,`${r.skippedConflicts.length} conflicts skipped`].join(", ")}.`}function Qn(r){return{pushed:[],pulled:[],remoteDeleted:[],localDeleted:[],skippedConflicts:[],hasError:!0,...r}}var mc=O(gt());function bw(r){let e=Number.parseInt(r,10);if(!Number.isFinite(e)||e<0||String(e)!==r.trim())throw new mc.InvalidArgumentError("--timeout must be a non-negative integer (milliseconds).");return e}async function Rw(r,e={}){let t=e.timeoutMs??3e4;if(!Number.isFinite(t)||t<0)return{ready:!1,error:`Invalid timeoutMs: must be a finite, non-negative number (got ${e.timeoutMs}).`};let n=e.profileManager??A();if(!n.getActiveProfile())return{ready:!1,error:M};let o=`${P(r)}_readiness-check`,s=Date.now();for(;Date.now()-s<t;){try{if((await n.authedRealmFetch(o,{method:"GET",headers:{Accept:"application/vnd.api+json"}})).ok)return{ready:!0}}catch{}let a=t-(Date.now()-s);if(a<=0)break;await new Promise(l=>setTimeout(l,Math.min(1e3,a)))}return{ready:!1,error:`Realm not ready after ${t}ms: ${o}`}}function dc(r){r.command("wait-for-ready").description("Poll a realm readiness-check endpoint until it responds OK or the timeout is reached").requiredOption("--realm <realm-url>","The realm URL to check").option("--timeout <ms>","Timeout in milliseconds (default: 30000)",bw).action(async e=>{let t;try{t=await Rw(e.realm,{timeoutMs:e.timeout})}catch(n){console.error(`${h}Error:${f} ${n instanceof Error?n.message:String(n)}`),process.exit(1)}t.ready?console.log(`${S}Realm is ready.${f}`):(console.error(`${h}Error:${f} ${t.error??"Realm not ready"}`),process.exit(1))})}var ai=O(gt()),Sc=O(require("fs/promises")),fr=O(require("path"));var ve=O(require("fs/promises")),pc=O(require("path")),Sw=".boxel-watch.lock";function ti(r){return pc.join(r,Sw)}function ri(r){try{return process.kill(r,0),!0}catch(e){return e?.code==="EPERM"}}async function vw(r){try{let e=await ve.readFile(ti(r),"utf8"),t=JSON.parse(e);return typeof t.pid!="number"||typeof t.startedAt!="string"||typeof t.realmUrl!="string"?null:t}catch{return null}}async function hc(r,e){await ve.mkdir(r,{recursive:!0});let t=await vw(r),n=!1;if(t&&ri(t.pid))return{ok:!1,existing:t};t&&(n=!0);let i={pid:process.pid,startedAt:new Date().toISOString(),realmUrl:e};return await ve.writeFile(ti(r),JSON.stringify(i,null,2)+`
100
+ `),{ok:!0,staleOverwrote:n}}async function ur(r){try{await ve.unlink(ti(r))}catch(e){if(e?.code!=="ENOENT")throw e}}var xe=O(require("fs/promises")),gc=O(require("os")),ni=O(require("path"));function yc(){return ni.join(gc.homedir(),".boxel-cli")}function wc(){return ni.join(yc(),"watch-processes.json")}async function Ec(){try{let r=await xe.readFile(wc(),"utf8"),e=JSON.parse(r);return Array.isArray(e?.processes)?{processes:e.processes.filter(n=>typeof n?.pid=="number"&&typeof n?.workspace=="string"&&typeof n?.startedAt=="string")}:{processes:[]}}catch{return{processes:[]}}}async function ii(r){await xe.mkdir(yc(),{recursive:!0});let e=wc(),t=`${e}.${process.pid}.tmp`;await xe.writeFile(t,JSON.stringify(r,null,2)+`
101
+ `),await xe.rename(t,e)}async function $c(){let r=await Ec(),e=r.processes.filter(t=>ri(t.pid));return e.length!==r.processes.length&&await ii({processes:e}),{processes:e}}async function bc(r){let t=(await $c()).processes.filter(n=>n.pid!==process.pid);t.push({pid:process.pid,workspace:r,startedAt:new Date().toISOString()}),await ii({processes:t})}async function Rc(){let r=await Ec(),e=r.processes.filter(t=>t.pid!==process.pid);e.length!==r.processes.length&&await ii({processes:e})}async function oi(){return(await $c()).processes}var si=class extends oe{name;debounceMs;overwriteLocal;checkpointManager;lastKnownMtimes=new Map;pendingChanges=new Map;debounceTimer=null;isShutdown=!1;constructor(e,t,n){super({realmUrl:e.realmUrl,localDir:e.localDir},t),this.debounceMs=n.debounceMs,this.overwriteLocal=n.overwriteLocal??!1,this.checkpointManager=new U(e.localDir),this.name=Ow(this.normalizedRealmUrl)}async sync(){await this.poll(),await this.flushPending()}async getRemoteMtimes(){let e=`${this.normalizedRealmUrl}_mtimes`,t=await this.authenticator.authedRealmFetch(e,{headers:{Accept:"application/vnd.api+json"}});if(!t.ok)throw new Error(`_mtimes fetch failed for ${this.normalizedRealmUrl}: ${t.status} ${t.statusText}`);let n=await t.json(),i=new Map;for(let[o,s]of Object.entries(n.data?.attributes?.mtimes??{}))i.set(o.replace(this.normalizedRealmUrl,""),s);return i}get localDir(){return this.options.localDir}get realmUrl(){return this.normalizedRealmUrl}get pendingCount(){return this.pendingChanges.size}async initialize(){await this.getRemoteMtimes(),await this.checkpointManager.isInitialized()||await this.checkpointManager.init();let e=await pe(this.options.localDir);if(e&&e.realmUrl===this.normalizedRealmUrl&&e.remoteMtimes)for(let[t,n]of Object.entries(e.remoteMtimes))this.lastKnownMtimes.set(t,n)}async poll(){let e=await this.getRemoteMtimes(),t=!1;for(let[n,i]of e){if(D(n))continue;let o=this.lastKnownMtimes.get(n);o===void 0?this.recordPending(n,{status:"added",mtime:i})&&(t=!0):i>o&&this.recordPending(n,{status:"modified",mtime:i})&&(t=!0)}for(let n of this.lastKnownMtimes.keys())D(n)||e.has(n)||this.pendingChanges.get(n)?.status!=="deleted"&&(this.pendingChanges.set(n,{status:"deleted",mtime:0}),t=!0);return t}async flushPending(){if(this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.pendingChanges.size===0)return{pulled:[],deleted:[],skipped:[],checkpoint:null};let e=new Map(this.pendingChanges);this.pendingChanges.clear();let t=[],n=[],i=[],o=[],s=null;if(!this.overwriteLocal){let u=await pe(this.options.localDir);u&&u.realmUrl===this.normalizedRealmUrl&&(s=u)}for(let[u,c]of e){let m=fr.join(this.options.localDir,u);if(!this.overwriteLocal&&await this.localDivergesFromManifest(m,u,s,c.status)){i.push(u);continue}if(c.status==="deleted"){try{await Sc.unlink(m)}catch(d){if(d.code!=="ENOENT")throw d}n.push(u),o.push({file:u,status:"deleted"})}else await this.downloadFile(u,m),t.push(u),o.push({file:u,status:c.status})}let a=new Set(i);for(let[u,c]of e)a.has(u)||(c.status==="deleted"?this.lastKnownMtimes.delete(u):this.lastKnownMtimes.set(u,c.mtime));let l=null;return o.length>0&&(await this.persistManifest(t,n),l=await this.checkpointManager.createCheckpoint("remote",o)),{pulled:t,deleted:n,skipped:i,checkpoint:l}}async localDivergesFromManifest(e,t,n,i){let o;try{o=await Z(e)}catch(a){if(a.code!=="ENOENT")throw a;return i==="deleted"?!1:n?.files[t]!==void 0}let s=n?.files[t];return s===void 0?!0:o!==s}scheduleFlush(e){this.isShutdown||(this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(async()=>{this.debounceTimer=null;try{let t=await this.flushPending();e?.(t)}catch(t){console.error(`${h}[${this.name}] Error applying changes:${f}`,t)}},this.debounceMs))}shutdown(){this.isShutdown=!0,this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}recordPending(e,t){let n=this.pendingChanges.get(e);return n&&n.mtime===t.mtime?!1:(this.pendingChanges.set(e,t),!0)}async persistManifest(e,t){let n=await pe(this.options.localDir),i=n&&n.realmUrl===this.normalizedRealmUrl?n.files:null,o=i?{...i}:{};for(let l of t)delete o[l];for(let l of e){let u=fr.join(this.options.localDir,l);try{o[l]=await Z(u)}catch(c){if(c.code!=="ENOENT")throw c}}let s={};for(let[l,u]of this.lastKnownMtimes)u!==0&&(s[l]=u);let a={realmUrl:this.normalizedRealmUrl,files:o};Object.keys(s).length>0&&(a.remoteMtimes=s),await Se(this.options.localDir,a)}};async function xw(r,e={}){if(r.length===0)return{watchers:[],error:"No realms provided to watch."};let t=e.intervalMs??3e4,n=e.debounceMs??5e3,i=e.quiet??!1,o=e.overwriteLocal??!1;if(!Number.isFinite(t)||t<=0)return{watchers:[],error:"`intervalMs` must be a positive number."};if(!Number.isFinite(n)||n<0)return{watchers:[],error:"`debounceMs` must be a non-negative number."};let s;if(e.authenticator)s=e.authenticator;else{let p=de({realmUrl:r[0].realmUrl,realmSecretSeed:e.realmSecretSeed,profileManager:e.profileManager});if(!p.ok)return{watchers:[],error:p.error};s=p.authenticator}let a=[];for(let p of r){let w=await hc(p.localDir,p.realmUrl);if(!w.ok){for(let v of a)await ur(v);return{watchers:[],error:_w(p.localDir,w.existing)}}w.staleOverwrote&&!i&&console.log(`${g}[${mr()}] overwrote stale lock at ${p.localDir}${f}`),a.push(p.localDir)}let l=[];for(let p of r){let w=new si(p,s,{debounceMs:n,overwriteLocal:o});try{await w.initialize()}catch(v){for(let B of l)B.shutdown();for(let B of a)await ur(B);return{watchers:[],error:`Failed to initialize watch on ${p.realmUrl}: ${v instanceof Error?v.message:String(v)}`}}l.push(w)}if(!i){console.log(`${_}\u21C5 Watching ${l.length} realm${l.length>1?"s":""}:${f}`);for(let p of l)console.log(` ${p.name} ${g}\u2192${f} ${p.localDir}`);console.log(` ${g}Interval: ${t/1e3}s, Debounce: ${n/1e3}s${f}`),console.log(` ${g}Press Ctrl+C to stop${f}
102
+ `)}let u=async()=>{await Promise.all(l.map(async p=>{try{await p.poll()&&(i||console.log(`${g}[${mr()}]${f} [${p.name}] ${C}\u26A1 ${p.pendingCount} change(s) detected${f}`),p.scheduleFlush(v=>{i||kw(p.name,v)}))}catch(w){console.error(`${h}[${p.name}] poll error:${f}`,w instanceof Error?w.message:w)}}))},c=!1,m=null,d=()=>{c||(m=setTimeout(async()=>{m=null,!c&&(await u(),d())},t))};try{await bc(r.map(p=>p.localDir).join(", "))}catch{}return await u(),d(),await new Promise(p=>{let w=null,v=null,B=async()=>{if(!c){c=!0,m!==null&&(clearTimeout(m),m=null);for(let we of l)we.shutdown();w&&process.off("SIGINT",w),v&&process.off("SIGTERM",v);for(let we of a)try{await ur(we)}catch{}try{await Rc()}catch{}p()}};if(e.signal){if(e.signal.aborted){B();return}e.signal.addEventListener("abort",()=>void B(),{once:!0})}else w=()=>{i||console.log(`
103
+ ${_}\u21C5 Watch stopped${f}`),B()},v=w,process.on("SIGINT",w),process.on("SIGTERM",v)}),{watchers:l}}function _w(r,e){return`A boxel realm watch process is already active for ${r} (pid ${e.pid}, started ${e.startedAt}). Stop it before starting a new one, or remove ${fr.join(r,".boxel-watch.lock")} if it's stale.`}function kw(r,e){let t=e.pulled.length+e.deleted.length;if(t>0&&(console.log(`${g}[${mr()}]${f} [${r}] ${S}applied ${t} change(s)${f} (${e.pulled.length} pulled, ${e.deleted.length} deleted)`),e.checkpoint)){let n=e.checkpoint.isMajor?"[MAJOR]":"[minor]";console.log(` ${g}Checkpoint:${f} ${e.checkpoint.shortHash} ${n} ${e.checkpoint.message}`)}for(let n of e.skipped)console.log(`${g}[${mr()}]${f} [${r}] ${C}\u26A0 skipped ${n}: local diverges from sync manifest (rerun with --overwrite-local to discard, or \`boxel realm sync\` to reconcile)${f}`)}function Ow(r){return r.replace(/\/$/,"").split("/").slice(-2).join("/")}function mr(){return new Date().toLocaleTimeString()}function Cw(r){return e=>{let t=Number.parseFloat(e);if(!Number.isFinite(t)||t<=0)throw new ai.InvalidArgumentError(`${r} must be a positive number.`);return t}}function Aw(r){return e=>{let t=Number.parseFloat(e);if(!Number.isFinite(t)||t<0)throw new ai.InvalidArgumentError(`${r} must be a non-negative number.`);return t}}function vc(r){r.command("start").description("Start watching a Boxel realm for server-side changes and pull them into a local directory").argument("<realm-url>","The URL of the realm to watch (e.g., https://app.boxel.ai/demo/)").argument("<local-dir>","The local directory to write changes into").option("-i, --interval <seconds>","Polling interval in seconds",Cw("--interval"),30).option("-d, --debounce <seconds>","Seconds to wait after a burst of changes before applying them",Aw("--debounce"),5).option("--realm-secret-seed","Administrative auth: prompt for a realm secret seed and mint a JWT locally instead of using a Matrix profile (env: BOXEL_REALM_SECRET_SEED)").option("--overwrite-local","Overwrite local files when the remote changes. Default: skip + warn when the local copy diverges from the sync manifest.").action(async(e,t,n)=>{let i=await me(n.realmSecretSeed===!0),o=await xw([{realmUrl:e,localDir:t}],{intervalMs:n.interval*1e3,debounceMs:n.debounce*1e3,realmSecretSeed:i,overwriteLocal:n.overwriteLocal===!0});o.error&&(console.error(`${h}Error:${f} ${o.error}`),process.exit(1))})}var li=require("child_process");var Pw=200;function Tw(r){return new Promise(e=>setTimeout(e,r))}function xc(r){try{if(process.platform==="win32")try{process.kill(r)}catch{(0,li.execSync)(`taskkill /PID ${r} /F`,{stdio:"ignore"})}else process.kill(r,"SIGINT");return{ok:!0,alreadyGone:!1}}catch(e){return e?.code==="ESRCH"?{ok:!0,alreadyGone:!0}:{ok:!1,alreadyGone:!1}}}function Lw(){if(process.platform==="win32")return[];let r;try{r=(0,li.execSync)('ps aux | grep -E "(tsx[[:space:]].*src/index\\.ts[[:space:]]+realm[[:space:]]+watch[[:space:]]+start|[[:space:]]boxel[[:space:]]+realm[[:space:]]+watch[[:space:]]+start|node[[:space:]].*boxel[[:space:]]+realm[[:space:]]+watch[[:space:]]+start)" | grep -v grep | grep -v "[[:space:]]stop"',{encoding:"utf8"}).trim()}catch{return[]}if(!r)return[];let e=[],t=new Set;for(let n of r.split(`
104
+ `)){if(!n)continue;let i=n.trim().split(/\s+/),o=Number.parseInt(i[1]??"",10);if(!Number.isFinite(o)||t.has(o))continue;t.add(o);let s=".",a=n.match(/\bstart\s+\S+\s+(\S+)/);a&&a[1]&&!a[1].startsWith("-")&&(s=a[1]),e.push({pid:o,workspace:s})}return e}async function Iw(){let r=[],e=[],t=new Set,n=await oi();for(let i of n){if(i.pid===process.pid)continue;t.add(i.pid);let o=xc(i.pid),s={pid:i.pid,workspace:i.workspace};o.ok?r.push(s):e.push(s)}for(let i of Lw()){if(i.pid===process.pid||t.has(i.pid))continue;t.add(i.pid);let o=xc(i.pid),s={pid:i.pid,workspace:i.workspace};o.ok?r.push(s):e.push(s)}return r.length>0&&(await Tw(Pw),await oi()),{stopped:r,failed:e}}function Mw(r){if(r.stopped.length===0&&r.failed.length===0){console.log("No running watch processes found.");return}for(let e of r.stopped)console.log(` ${g}\u21C5${f} Stopped: boxel realm watch ${e.workspace} (PID ${e.pid})`);for(let e of r.failed)console.log(` ${h}\xD7${f} Failed to stop: boxel realm watch ${e.workspace} (PID ${e.pid})`);if(r.stopped.length>0){let e=r.stopped.length>1?"es":"";console.log(`
105
+ ${S}\u2713 Stopped ${r.stopped.length} process${e}${f}`)}}function _c(r){r.command("stop").description("Stop all running boxel realm watch processes").action(async()=>{let e=await Iw();Mw(e)})}function kc(r){let e=r.command("watch").description("Watch a Boxel realm; subcommands manage watch processes");vc(e),_c(e)}function Oc(r){let e=r.command("realm").description("Manage realms on the realm server");Ol(e),Tl(e),zl(e),Jl(e),Ql(e),rc(e),ic(e),sc(e);let t=fc(e);uc(t),dc(e),kc(e)}async function Nw(r,e,t){let n=t?.profileManager??A();if(!n.getActiveProfile())return{ok:!1,error:M};if(D(e))return{ok:!1,error:`Cannot delete protected file: ${e}`};let o=new URL(e,P(r)).href,s;try{s=await n.authedRealmFetch(o,{method:"DELETE",headers:{Accept:"application/vnd.card+source"}})}catch(a){return{ok:!1,error:a instanceof Error?a.message:String(a)}}if(!s.ok){let a=await s.text().catch(()=>"(no body)");return{ok:!1,error:`HTTP ${s.status}: ${a.slice(0,300)}`}}return{ok:!0}}function Cc(r){r.command("delete").description("Delete a file from a realm").argument("<path>","Realm-relative file path to delete").requiredOption("--realm <realm-url>","The realm URL to delete from").option("--json","Output raw JSON response").action(async(e,t)=>{let n;try{n=await Nw(t.realm,e)}catch(i){console.error(`${h}Error:${f} ${i instanceof Error?i.message:String(i)}`),process.exit(1)}t.json?N.output(JSON.stringify(n,null,2)):n.ok?console.log(`${g}Deleted:${f} ${e}`):console.error(`${h}Error:${f} ${n.error}`),n.ok||process.exit(1)})}async function ci(r,e){let t=e?.profileManager??A();if(!t.getActiveProfile())return{filenames:[],error:M};let i=P(r),o=`${i}_mtimes`;try{let s=await t.authedRealmFetch(o,{method:"GET",headers:{Accept:"application/vnd.api+json"}});if(!s.ok){let c=await s.text().catch(()=>"(no body)");return{filenames:[],error:`_mtimes returned HTTP ${s.status}: ${c.slice(0,300)}`}}let a=await s.json(),l=a?.data?.attributes?.mtimes??a,u=[];for(let c of Object.keys(l)){if(!c.startsWith(i))continue;let m=c.slice(i.length);!m||m.endsWith("/")||u.push(m)}return{filenames:u.sort()}}catch(s){return{filenames:[],error:s instanceof Error?s.message:String(s)}}}function Ac(r){r.command("list").alias("ls").description("List all files in a realm").requiredOption("--realm <realm-url>","The realm URL to list files from").option("--json","Output raw JSON response").action(async e=>{let t;try{t=await ci(e.realm)}catch(n){console.error(`${h}Error:${f} ${n instanceof Error?n.message:String(n)}`),process.exit(1)}if(e.json)N.output(JSON.stringify(t,null,2)),t.error&&process.exit(1);else if(t.error)console.error(`${h}Error:${f} ${t.error}`),process.exit(1);else{for(let n of t.filenames)console.log(`${g}${n}${f}`);console.log(`
106
+ ${g}${t.filenames.length} file(s)${f}`)}})}var dr=require("fs");var Pc=require("fs");async function ut(r,e,t,n){let i=n?.profileManager??A();if(!i.getActiveProfile())return{ok:!1,error:M};let s=new URL(e,P(r)).href;try{let a=await i.authedRealmFetch(s,{method:"POST",headers:{Accept:"application/vnd.card+source","Content-Type":"application/vnd.card+source"},body:t});if(!a.ok){let l=await a.text().catch(()=>"(no body)");return{ok:!1,error:`HTTP ${a.status}: ${l.slice(0,300)}`}}return{ok:!0}}catch(a){return{ok:!1,error:a instanceof Error?a.message:String(a)}}}function ct(r){process.stderr.write(r+`
107
+ `)}async function Dw(){let r=[];for await(let e of process.stdin)r.push(e);return Buffer.concat(r).toString("utf-8")}function Tc(r){r.command("write").description("Write a file to a realm (reads content from STDIN or --file)").argument("<path>","Realm-relative file path (e.g., hello.gts, Cards/my-card.json)").requiredOption("--realm <realm-url>","The realm URL to write to").option("--file <filepath>","Read content from a local file instead of STDIN").option("--json","Output raw JSON response").action(async(e,t)=>{let n;if(t.file)try{n=(0,Pc.readFileSync)(t.file,"utf-8")}catch(o){ct(`${h}Error:${f} Could not read file: ${o instanceof Error?o.message:String(o)}`),process.exit(1)}else process.stdin.isTTY&&ct(`${g}Reading from STDIN. Type or paste content, then press Enter followed by Ctrl+D to finish.${f}`),n=await Dw(),ct(`${g}Received ${n.length} bytes. Writing to realm...${f}`);let i;try{i=await ut(t.realm,e,n)}catch(o){ct(`${h}Error:${f} ${o instanceof Error?o.message:String(o)}`),process.exit(1)}t.json?N.output(JSON.stringify(i,null,2)):i.ok?console.log(`${S}Written:${f} ${e} ${g}\u2192${f} ${t.realm}`):ct(`${h}Error:${f} ${i.error}`),i.ok||process.exit(1)})}async function Fw(r,e,t,n){let i=n?.profileManager??A();if(!i.getActiveProfile())return{ok:!1,error:M};let s=`${P(r)}_lint`;try{let a=await i.authedRealmFetch(s,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/vnd.card+source","X-Filename":t,"X-HTTP-Method-Override":"QUERY"},body:e});if(!a.ok){let u=await a.text().catch(()=>"(no body)");return{ok:!1,error:`HTTP ${a.status}: ${u.slice(0,300)}`}}let l=await a.json();return{ok:!0,fixed:l.fixed,output:l.output,messages:l.messages}}catch(a){return{ok:!1,error:a instanceof Error?a.message:String(a)}}}function Lc(r){r.command("lint").description("Lint a file in a realm using the realm lint endpoint").argument("<path>","Realm-relative file path to lint (e.g., my-card.gts)").requiredOption("--realm <realm-url>","The realm URL to lint against").option("--file <local-filepath>","Read source from a local file instead of fetching from the realm").option("--json","Output raw JSON response").option("--fix","Write auto-fixed output back to the source").action(async(e,t)=>{let n=A();n.getActiveProfile()||(console.error(`${h}Error:${f} ${M}`),process.exit(1));let o;if(t.file)try{o=(0,dr.readFileSync)(t.file,"utf-8")}catch(c){console.error(`${h}Error:${f} Could not read local file: ${c instanceof Error?c.message:String(c)}`),process.exit(1)}else{let c=new URL(e,P(t.realm)).href;try{let m=await n.authedRealmFetch(c,{method:"GET",headers:{Accept:"application/vnd.card+source"}});if(!m.ok){let d=await m.text().catch(()=>"(no body)");console.error(`${h}Error:${f} Could not read file from realm: HTTP ${m.status}: ${d.slice(0,300)}`),process.exit(1)}o=await m.text()}catch(m){console.error(`${h}Error:${f} ${m instanceof Error?m.message:String(m)}`),process.exit(1)}}let s;try{s=await Fw(t.realm,o,e,{profileManager:n})}catch(c){console.error(`${h}Error:${f} ${c instanceof Error?c.message:String(c)}`),process.exit(1)}if(t.json){N.output(JSON.stringify(s,null,2)),s.ok||process.exit(1);return}if(s.ok||(console.error(`${h}Error:${f} ${s.error}`),process.exit(1)),t.fix&&s.fixed&&s.output)if(t.file)(0,dr.writeFileSync)(t.file,s.output,"utf-8"),console.log(`${S}Fixed:${f} ${t.file}`);else{let c=await ut(t.realm,e,s.output,{profileManager:n});c.ok||(console.error(`${h}Error:${f} Could not write fixed file: ${c.error}`),process.exit(1)),console.log(`${S}Fixed:${f} ${e} ${g}\u2192${f} ${t.realm}`)}let a=s.messages??[],l=a.filter(c=>c.severity===2),u=a.filter(c=>c.severity===1);if(a.length===0){console.log(`${g}No lint issues found.${f}`);return}for(let c of a){let m=c.severity===2?h:C,d=c.severity===2?"error":"warning",p=c.ruleId?` (${c.ruleId})`:"";console.log(`${m}${d}${f} ${c.line}:${c.column} ${c.message}${g}${p}${f}`)}console.log(`
108
+ ${g}${l.length} error(s), ${u.length} warning(s)${f}`),l.length>0&&process.exit(1)})}async function ui(r,e,t){let n=t?.profileManager??A();if(!n.getActiveProfile())return{ok:!1,error:M};let o=new URL(e,P(r)).href,s;try{s=await n.authedRealmFetch(o,{method:"GET",headers:{Accept:"application/vnd.card+source"}})}catch(l){return{ok:!1,error:l instanceof Error?l.message:String(l)}}if(!s.ok){let l=await s.text().catch(()=>"(no body)");return{ok:!1,status:s.status,error:`HTTP ${s.status}: ${l.slice(0,300)}`}}let a=await s.text();return{ok:!0,status:s.status,content:a}}function Ic(r){r.command("read").description("Read a file from a realm").argument("<path>","Realm-relative file path (e.g., hello-world.json, Cards/my-card.gts)").requiredOption("--realm <realm-url>","The realm URL to read from").option("--json","Output raw JSON response").action(async(e,t)=>{let n;try{n=await ui(t.realm,e)}catch(i){console.error(`${h}Error:${f} ${i instanceof Error?i.message:String(i)}`),process.exit(1)}t.json?N.output(JSON.stringify(n,null,2)):n.ok?N.output(n.content??""):(console.error(`${g}Status:${f} ${n.status??"(no status)"}`),console.error(`${h}Error:${f} ${n.error}`)),n.ok||process.exit(1)})}var fi="// touched for re-index";async function Uw(r,e,t){let n=t?.profileManager??A();if(!n.getActiveProfile())return{ok:!1,touched:[],skipped:[],error:M};let o;if(t?.all){if(e.length>0)return{ok:!1,touched:[],skipped:[],error:"Cannot pass file paths together with --all"};let l=await ci(r,{profileManager:n});if(l.error)return{ok:!1,touched:[],skipped:[],error:l.error};o=l.filenames.filter(u=>(u.endsWith(".json")||u.endsWith(".gts"))&&!D(u))}else{if(e.length===0)return{ok:!1,touched:[],skipped:[],error:"No file paths provided. Pass paths or use --all."};o=e}let s=[],a=[];for(let l of o){if(!l.endsWith(".json")&&!l.endsWith(".gts")){a.push({path:l,reason:"unsupported extension"});continue}if(D(l)){a.push({path:l,reason:"protected file"});continue}let u=await ui(r,l,{profileManager:n});if(!u.ok||u.content==null){a.push({path:l,reason:u.error??"read failed"});continue}if(t?.dryRun){s.push(l);continue}let c=l.endsWith(".json")?jw(u.content):Gw(u.content),m=await ut(r,l,c,{profileManager:n});if(!m.ok){a.push({path:l,reason:m.error??"write failed"});continue}s.push(l)}return{ok:a.length===0,touched:s,skipped:a}}function jw(r){try{let e=JSON.parse(r);if(e?.data)return e.data.meta={...e.data.meta??{},_touched:Date.now()},JSON.stringify(e,null,2)+`
109
109
  `}catch{}return qw(r)}function qw(r){return r.endsWith(`
110
110
 
111
111
  `)?r.slice(0,-1):r+`
@@ -116,15 +116,15 @@ ${fi}
116
116
  `)?r+fi+`
117
117
  `:r+`
118
118
  `+fi+`
119
- `}function Mc(r){r.command("touch").description("Force realm re-indexing of one or more files by making a semantically-neutral edit. --all touches every .json/.gts in the realm without confirmation; use with care.").argument("[paths...]","Realm-relative file path(s) to touch (omit when using --all)").requiredOption("--realm <realm-url>","The realm URL to touch files in").option("--all","Touch every .json and .gts file in the realm").option("--dry-run","Print files that would be touched without writing").option("--json","Output raw JSON response").action(async(e,t)=>{let n;try{n=await Uw(t.realm,e,{all:t.all,dryRun:t.dryRun})}catch(i){console.error(`${h}Error:${f} ${i instanceof Error?i.message:String(i)}`),process.exit(1)}if(t.json)console.log(JSON.stringify(n,null,2));else if(n.error)console.error(`${h}Error:${f} ${n.error}`);else{let i=t.dryRun?`${y}[dry-run]${f} `:"";for(let s of n.touched)console.log(`${i}${S}touched${f} ${s}`);for(let{path:s,reason:a}of n.skipped)console.log(`${h}skipped${f} ${s} ${y}(${a})${f}`);let o=t.dryRun?"would touch":"touched";console.log(`
120
- ${y}${o} ${n.touched.length} file(s)${n.skipped.length>0?`, skipped ${n.skipped.length}`:""}${f}`)}n.ok||process.exit(1)})}function Nc(r){let e=r.command("file").description("Read, write, and manage files in a realm");Cc(e),Ac(e),Lc(e),Ic(e),Mc(e),Tc(e)}async function Vw(r,e,t){let n=t?.profileManager??A(),i=n.getActiveProfile();if(!i)throw new Error("No active profile. Run `boxel profile add` to create one.");let s=`${i.profile.realmServerUrl.replace(/\/$/,"")}/_run-command`,a={data:{type:"run-command",attributes:{realmURL:e,command:r,commandInput:t?.input??null}}},l;try{l=await n.authedRealmServerFetch(s,{method:"POST",headers:{"Content-Type":"application/vnd.api+json",Accept:"application/vnd.api+json"},body:JSON.stringify(a)})}catch(m){return{status:"error",error:`run-command fetch failed: ${m instanceof Error?m.message:String(m)}`}}if(!l.ok){let m=await l.text().catch(()=>"(no body)");return{status:"error",error:`run-command HTTP ${l.status}: ${m}`}}let u;try{u=await l.json()}catch{return{status:"error",error:`run-command response was not valid JSON (HTTP ${l.status})`}}let c=u.data?.attributes;return{status:c?.status??"error",result:c?.cardResultString??null,error:c?.error??null}}function Dc(r){r.command("run-command").description("Execute a host command on the realm server via the prerenderer").argument("<command-specifier>","Command module path (e.g. @cardstack/boxel-host/commands/get-card-type-schema/default)").requiredOption("--realm <realm-url>","The realm URL context for the command").option("--input <json>","JSON string of command input").option("--json","Output raw JSON response").action(async(e,t)=>{let n;if(t.input)try{let o=JSON.parse(t.input);(typeof o!="object"||o===null||Array.isArray(o))&&(console.error(`${h}Error:${f} --input must be a JSON object, got ${Array.isArray(o)?"array":typeof o}`),process.exit(1)),n=o}catch{console.error(`${h}Error:${f} --input is not valid JSON: ${t.input}`),process.exit(1)}let i;try{i=await Vw(e,t.realm,{input:n})}catch(o){console.error(`${h}Error:${f} ${o instanceof Error?o.message:String(o)}`),process.exit(1)}if(t.json)N.output(JSON.stringify(i,null,2));else{if(console.log(`${y}Status:${f} ${Hw(i.status)}${i.status}${f}`),i.result){console.log(`${y}Result:${f}`);try{N.output(JSON.stringify(JSON.parse(i.result),null,2))}catch{N.output(i.result)}}i.error&&console.error(`${h}Error:${f} ${i.error}`)}(i.status==="error"||i.status==="unusable")&&process.exit(1)})}function Hw(r){switch(r){case"ready":return S;case"error":return h;default:return _}}async function Ww(r,e,t){let n=t?.profileManager??A(),i=n.getActiveProfile();if(!i)return{ok:!1,error:M};let s=`${i.profile.realmServerUrl.replace(/\/$/,"")}/_federated-search`,a=(Array.isArray(r)?r:[r]).map(P);try{let l=await n.authedRealmServerFetch(s,{method:"QUERY",headers:{Accept:"application/vnd.card+json","Content-Type":"application/json"},body:JSON.stringify({realms:a,...e})});if(!l.ok){let c=await l.text();return{ok:!1,status:l.status,error:`HTTP ${l.status}: ${c.slice(0,300)}`}}let u=await l.json();return{ok:!0,status:l.status,data:u.data}}catch(l){return{ok:!1,status:0,error:l instanceof Error?l.message:String(l)}}}function Fc(r){r.command("search").description("Federated search across realms using a JSON query").requiredOption("--realm <realm-url>","Realm URL to search (repeatable)",(e,t)=>(t.push(e),t),[]).requiredOption("--query <json>","JSON query object (as a string)").option("--json","Output raw JSON response").action(async e=>{e.realm.length===0&&(console.error(`${h}Error:${f} At least one --realm is required`),process.exit(1));let t;try{let i=JSON.parse(e.query);(typeof i!="object"||i===null||Array.isArray(i))&&(console.error(`${h}Error:${f} --query must be a JSON object, got ${Array.isArray(i)?"array":typeof i}`),process.exit(1)),t=i}catch(i){console.error(`${h}Error:${f} Invalid JSON in --query: ${i instanceof Error?i.message:String(i)}`),process.exit(1);return}let n;try{n=await Ww(e.realm,t)}catch(i){console.error(`${h}Error:${f} ${i instanceof Error?i.message:String(i)}`),process.exit(1);return}e.json?N.output(JSON.stringify(n,null,2)):n.ok?N.output(JSON.stringify(n.data??[],null,2)):(console.error(`${y}Status:${f} ${n.status??"(no status)"}`),console.error(`${h}Error:${f} ${n.error}`)),n.ok||process.exit(1)})}function jc(r){let e=new Uc.Command;return e.name("boxel").description("CLI tools for Boxel workspace management").version(r).option("-q, --quiet","Suppress informational progress logs (info/log/debug). Errors and warnings, plus command result payloads (JSON, file contents), are still emitted. Use this when invoking the CLI from automation (e.g. the software factory test harness) to keep stdout focused on the result.").hook("preAction",t=>{(t.optsWithGlobals?.()??t.opts()).quiet&&Zt(!0),xl(process.cwd())}),e.command("profile").description("Manage saved profiles for different users/environments").argument("[subcommand]","list | add | switch | remove | migrate").argument("[arg]","Profile ID (for switch/remove)").option("-u, --user <matrixId>","Matrix user ID (e.g., @user:boxel.ai)").option("-p, --password <password>","Password (for add command)").option("-n, --name <displayName>","Display name (for add command)").option("-m, --matrix-url <url>","Matrix server URL (for add command with non-standard domains)").option("-r, --realm-server-url <url>","Realm server URL (for add command with non-standard domains)").addHelpText("after",`
119
+ `}function Mc(r){r.command("touch").description("Force realm re-indexing of one or more files by making a semantically-neutral edit. --all touches every .json/.gts in the realm without confirmation; use with care.").argument("[paths...]","Realm-relative file path(s) to touch (omit when using --all)").requiredOption("--realm <realm-url>","The realm URL to touch files in").option("--all","Touch every .json and .gts file in the realm").option("--dry-run","Print files that would be touched without writing").option("--json","Output raw JSON response").action(async(e,t)=>{let n;try{n=await Uw(t.realm,e,{all:t.all,dryRun:t.dryRun})}catch(i){console.error(`${h}Error:${f} ${i instanceof Error?i.message:String(i)}`),process.exit(1)}if(t.json)console.log(JSON.stringify(n,null,2));else if(n.error)console.error(`${h}Error:${f} ${n.error}`);else{let i=t.dryRun?`${g}[dry-run]${f} `:"";for(let s of n.touched)console.log(`${i}${S}touched${f} ${s}`);for(let{path:s,reason:a}of n.skipped)console.log(`${h}skipped${f} ${s} ${g}(${a})${f}`);let o=t.dryRun?"would touch":"touched";console.log(`
120
+ ${g}${o} ${n.touched.length} file(s)${n.skipped.length>0?`, skipped ${n.skipped.length}`:""}${f}`)}n.ok||process.exit(1)})}function Nc(r){let e=r.command("file").description("Read, write, and manage files in a realm");Cc(e),Ac(e),Lc(e),Ic(e),Mc(e),Tc(e)}async function Vw(r,e,t){let n=t?.profileManager??A(),i=n.getActiveProfile();if(!i)throw new Error("No active profile. Run `boxel profile add` to create one.");let s=`${i.profile.realmServerUrl.replace(/\/$/,"")}/_run-command`,a={data:{type:"run-command",attributes:{realmURL:e,command:r,commandInput:t?.input??null}}},l;try{l=await n.authedRealmServerFetch(s,{method:"POST",headers:{"Content-Type":"application/vnd.api+json",Accept:"application/vnd.api+json"},body:JSON.stringify(a)})}catch(m){return{status:"error",error:`run-command fetch failed: ${m instanceof Error?m.message:String(m)}`}}if(!l.ok){let m=await l.text().catch(()=>"(no body)");return{status:"error",error:`run-command HTTP ${l.status}: ${m}`}}let u;try{u=await l.json()}catch{return{status:"error",error:`run-command response was not valid JSON (HTTP ${l.status})`}}let c=u.data?.attributes;return{status:c?.status??"error",result:c?.cardResultString??null,error:c?.error??null}}function Dc(r){r.command("run-command").description("Execute a host command on the realm server via the prerenderer").argument("<command-specifier>","Command module path (e.g. @cardstack/boxel-host/commands/get-card-type-schema/default)").requiredOption("--realm <realm-url>","The realm URL context for the command").option("--input <json>","JSON string of command input").option("--json","Output raw JSON response").action(async(e,t)=>{let n;if(t.input)try{let o=JSON.parse(t.input);(typeof o!="object"||o===null||Array.isArray(o))&&(console.error(`${h}Error:${f} --input must be a JSON object, got ${Array.isArray(o)?"array":typeof o}`),process.exit(1)),n=o}catch{console.error(`${h}Error:${f} --input is not valid JSON: ${t.input}`),process.exit(1)}let i;try{i=await Vw(e,t.realm,{input:n})}catch(o){console.error(`${h}Error:${f} ${o instanceof Error?o.message:String(o)}`),process.exit(1)}if(t.json)N.output(JSON.stringify(i,null,2));else{if(console.log(`${g}Status:${f} ${Hw(i.status)}${i.status}${f}`),i.result){console.log(`${g}Result:${f}`);try{N.output(JSON.stringify(JSON.parse(i.result),null,2))}catch{N.output(i.result)}}i.error&&console.error(`${h}Error:${f} ${i.error}`)}(i.status==="error"||i.status==="unusable")&&process.exit(1)})}function Hw(r){switch(r){case"ready":return S;case"error":return h;default:return _}}async function Ww(r,e,t){let n=t?.profileManager??A(),i=n.getActiveProfile();if(!i)return{ok:!1,error:M};let s=`${i.profile.realmServerUrl.replace(/\/$/,"")}/_federated-search`,a=(Array.isArray(r)?r:[r]).map(P);try{let l=await n.authedRealmServerFetch(s,{method:"QUERY",headers:{Accept:"application/vnd.card+json","Content-Type":"application/json"},body:JSON.stringify({realms:a,...e})});if(!l.ok){let c=await l.text();return{ok:!1,status:l.status,error:`HTTP ${l.status}: ${c.slice(0,300)}`}}let u=await l.json();return{ok:!0,status:l.status,data:u.data}}catch(l){return{ok:!1,status:0,error:l instanceof Error?l.message:String(l)}}}function Fc(r){r.command("search").description("Federated search across realms using a JSON query").requiredOption("--realm <realm-url>","Realm URL to search (repeatable)",(e,t)=>(t.push(e),t),[]).requiredOption("--query <json>","JSON query object (as a string)").option("--json","Output raw JSON response").action(async e=>{e.realm.length===0&&(console.error(`${h}Error:${f} At least one --realm is required`),process.exit(1));let t;try{let i=JSON.parse(e.query);(typeof i!="object"||i===null||Array.isArray(i))&&(console.error(`${h}Error:${f} --query must be a JSON object, got ${Array.isArray(i)?"array":typeof i}`),process.exit(1)),t=i}catch(i){console.error(`${h}Error:${f} Invalid JSON in --query: ${i instanceof Error?i.message:String(i)}`),process.exit(1);return}let n;try{n=await Ww(e.realm,t)}catch(i){console.error(`${h}Error:${f} ${i instanceof Error?i.message:String(i)}`),process.exit(1);return}e.json?N.output(JSON.stringify(n,null,2)):n.ok?N.output(JSON.stringify(n.data??[],null,2)):(console.error(`${g}Status:${f} ${n.status??"(no status)"}`),console.error(`${h}Error:${f} ${n.error}`)),n.ok||process.exit(1)})}function jc(r){let e=new Uc.Command;return e.name("boxel").description("CLI tools for Boxel workspace management").version(r).option("-q, --quiet","Suppress informational progress logs (info/log/debug). Errors and warnings, plus command result payloads (JSON, file contents), are still emitted. Use this when invoking the CLI from automation (e.g. the software factory test harness) to keep stdout focused on the result.").hook("preAction",t=>{(t.optsWithGlobals?.()??t.opts()).quiet&&Qt(!0),xl(process.cwd())}),e.command("profile").description("Manage saved profiles for different users/environments").argument("[subcommand]","list | add | switch | remove | migrate").argument("[arg]","Profile ID (for switch/remove)").option("-u, --user <matrixId>","Matrix user ID (e.g., @user:boxel.ai)").option("-p, --password <password>","Password (for add command)").option("-n, --name <displayName>","Display name (for add command)").option("-m, --matrix-url <url>","Matrix server URL (for add command with non-standard domains)").option("-r, --realm-server-url <url>","Realm server URL (for add command with non-standard domains)").addHelpText("after",`
121
121
  Environment variables (for 'add'):
122
122
  BOXEL_PASSWORD Password; preferred over -p to avoid shell history.
123
123
  BOXEL_ENVIRONMENT An env-mode slug (e.g. a branch name), interpreted
124
124
  like scripts/env-slug.sh: URLs are derived as
125
125
  http://matrix.<slug>.localhost and
126
126
  http://realm-server.<slug>.localhost/. Overridden
127
- by --matrix-url / --realm-server-url if provided.`).action(async(t,n,i)=>{i?.password&&console.warn('Warning: Supplying a password via -p/--password may expose it in shell history and process listings. For non-interactive usage, prefer the BOXEL_PASSWORD environment variable or use "boxel profile add" interactively.'),await bl(t,n,i)}),Nc(e),Oc(e),Dc(e),Fc(e),kl(e),_l(e),e}var Bw=JSON.parse((0,qc.readFileSync)((0,Gc.resolve)(__dirname,"../package.json"),"utf-8"));process.argv.includes("--quiet")&&Zt(!0);jc(Bw.version).parse();
127
+ by --matrix-url / --realm-server-url if provided.`).action(async(t,n,i)=>{i?.password&&console.warn('Warning: Supplying a password via -p/--password may expose it in shell history and process listings. For non-interactive usage, prefer the BOXEL_PASSWORD environment variable or use "boxel profile add" interactively.'),await bl(t,n,i)}),Nc(e),Oc(e),Dc(e),Fc(e),kl(e),_l(e),e}var Bw=JSON.parse((0,qc.readFileSync)((0,Gc.resolve)(__dirname,"../package.json"),"utf-8"));process.argv.includes("--quiet")&&Qt(!0);jc(Bw.version).parse();
128
128
  /*! Bundled license information:
129
129
 
130
130
  safe-buffer/index.js: