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

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,114 +1,130 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var tc=Object.create;var qn=Object.defineProperty;var rc=Object.getOwnPropertyDescriptor;var nc=Object.getOwnPropertyNames;var ic=Object.getPrototypeOf,sc=Object.prototype.hasOwnProperty;var h=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var oc=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of nc(e))!sc.call(r,i)&&i!==t&&qn(r,i,{get:()=>e[i],enumerable:!(n=rc(e,i))||n.enumerable});return r};var N=(r,e,t)=>(t=r!=null?tc(ic(r)):{},oc(e||!r||!r.__esModule?qn(t,"default",{value:r,enumerable:!0}):t,r));var Vn=h((Ry,ac)=>{ac.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 Yn=h(($y,le)=>{var Zt=require("fs"),it=require("path"),lc=require("os"),cc=require("crypto"),uc=Vn(),er=uc.version,fc=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function mc(r){let e={},t=r.toString();t=t.replace(/\r\n?/mg,`
3
- `);let n;for(;(n=fc.exec(t))!=null;){let i=n[1],s=n[2]||"";s=s.trim();let o=s[0];s=s.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),o==='"'&&(s=s.replace(/\\n/g,`
4
- `),s=s.replace(/\\r/g,"\r")),e[i]=s}return e}function dc(r){r=r||{};let e=Bn(r);r.path=e;let t=U.configDotenv(r);if(!t.parsed){let o=new Error(`MISSING_DATA: Cannot parse ${e} for an unknown reason`);throw o.code="MISSING_DATA",o}let n=Wn(r).split(","),i=n.length,s;for(let o=0;o<i;o++)try{let a=n[o].trim(),l=hc(t,a);s=U.decrypt(l.ciphertext,l.key);break}catch(a){if(o+1>=i)throw a}return U.parse(s)}function pc(r){console.log(`[dotenv@${er}][WARN] ${r}`)}function Me(r){console.log(`[dotenv@${er}][DEBUG] ${r}`)}function Hn(r){console.log(`[dotenv@${er}] ${r}`)}function Wn(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 hc(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 s=`DOTENV_VAULT_${i.toUpperCase()}`,o=r.parsed[s];if(!o){let a=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${s} in your .env.vault file.`);throw a.code="NOT_FOUND_DOTENV_ENVIRONMENT",a}return{ciphertext:o,key:n}}function Bn(r){let e=null;if(r&&r.path&&r.path.length>0)if(Array.isArray(r.path))for(let t of r.path)Zt.existsSync(t)&&(e=t.endsWith(".vault")?t:`${t}.vault`);else e=r.path.endsWith(".vault")?r.path:`${r.path}.vault`;else e=it.resolve(process.cwd(),".env.vault");return Zt.existsSync(e)?e:null}function Gn(r){return r[0]==="~"?it.join(lc.homedir(),r.slice(1)):r}function gc(r){let e=!!(r&&r.debug),t=r&&"quiet"in r?r.quiet:!0;(e||!t)&&Hn("Loading env from encrypted .env.vault");let n=U._parseVault(r),i=process.env;return r&&r.processEnv!=null&&(i=r.processEnv),U.populate(i,n,r),{parsed:n}}function yc(r){let e=it.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&&Me("No encoding is specified. UTF-8 is used by default");let s=[e];if(r&&r.path)if(!Array.isArray(r.path))s=[Gn(r.path)];else{s=[];for(let u of r.path)s.push(Gn(u))}let o,a={};for(let u of s)try{let c=U.parse(Zt.readFileSync(u,{encoding:t}));U.populate(a,c,r)}catch(c){n&&Me(`Failed to load ${u} ${c.message}`),o=c}let l=process.env;if(r&&r.processEnv!=null&&(l=r.processEnv),U.populate(l,a,r),n||!i){let u=Object.keys(a).length,c=[];for(let f of s)try{let d=it.relative(process.cwd(),f);c.push(d)}catch(d){n&&Me(`Failed to load ${f} ${d.message}`),o=d}Hn(`injecting env (${u}) from ${c.join(",")}`)}return o?{parsed:a,error:o}:{parsed:a}}function Ec(r){if(Wn(r).length===0)return U.configDotenv(r);let e=Bn(r);return e?U._configVault(r):(pc(`You set DOTENV_KEY but you are missing a .env.vault file at ${e}. Did you forget to build it?`),U.configDotenv(r))}function wc(r,e){let t=Buffer.from(e.slice(-64),"hex"),n=Buffer.from(r,"base64"),i=n.subarray(0,12),s=n.subarray(-16);n=n.subarray(12,-16);try{let o=cc.createDecipheriv("aes-256-gcm",t,i);return o.setAuthTag(s),`${o.update(n)}${o.final()}`}catch(o){let a=o instanceof RangeError,l=o.message==="Invalid key length",u=o.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 o}}function bc(r,e,t={}){let n=!!(t&&t.debug),i=!!(t&&t.override);if(typeof e!="object"){let s=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw s.code="OBJECT_REQUIRED",s}for(let s of Object.keys(e))Object.prototype.hasOwnProperty.call(r,s)?(i===!0&&(r[s]=e[s]),n&&Me(i===!0?`"${s}" is already defined and WAS overwritten`:`"${s}" is already defined and was NOT overwritten`)):r[s]=e[s]}var U={configDotenv:yc,_configVault:gc,_parseVault:dc,config:Ec,decrypt:wc,parse:mc,populate:bc};le.exports.configDotenv=U.configDotenv;le.exports._configVault=U._configVault;le.exports._parseVault=U._parseVault;le.exports.config=U.config;le.exports.decrypt=U.decrypt;le.exports.parse=U.parse;le.exports.populate=U.populate;le.exports=U});var zn=h((vy,Xn)=>{var we={};process.env.DOTENV_CONFIG_ENCODING!=null&&(we.encoding=process.env.DOTENV_CONFIG_ENCODING);process.env.DOTENV_CONFIG_PATH!=null&&(we.path=process.env.DOTENV_CONFIG_PATH);process.env.DOTENV_CONFIG_QUIET!=null&&(we.quiet=process.env.DOTENV_CONFIG_QUIET);process.env.DOTENV_CONFIG_DEBUG!=null&&(we.debug=process.env.DOTENV_CONFIG_DEBUG);process.env.DOTENV_CONFIG_OVERRIDE!=null&&(we.override=process.env.DOTENV_CONFIG_OVERRIDE);process.env.DOTENV_CONFIG_DOTENV_KEY!=null&&(we.DOTENV_KEY=process.env.DOTENV_CONFIG_DOTENV_KEY);Xn.exports=we});var Kn=h((Sy,Jn)=>{var Rc=/^dotenv_config_(encoding|path|quiet|debug|override|DOTENV_KEY)=(.+)$/;Jn.exports=function(e){let t=e.reduce(function(n,i){let s=i.match(Rc);return s&&(n[s[1]]=s[2]),n},{});return"quiet"in t||(t.quiet="true"),t}});var De=h(rr=>{var st=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}},tr=class extends st{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};rr.CommanderError=st;rr.InvalidArgumentError=tr});var ot=h(ir=>{var{InvalidArgumentError:$c}=De(),nr=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 $c(`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 vc(r){let e=r.name()+(r.variadic===!0?"...":"");return r.required?"<"+e+">":"["+e+"]"}ir.Argument=nr;ir.humanReadableArgName=vc});var ar=h(or=>{var{humanReadableArgName:Sc}=ot(),sr=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,s)=>i.name().localeCompare(s.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),s=n.long&&e._findOption(n.long);!i&&!s?t.push(n):n.long&&!s?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(s=>!s.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=>Sc(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 s(f,d){return t.formatItem(f,n,d,t)}let o=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],a=t.commandDescription(e);a.length>0&&(o=o.concat([t.boxWrap(t.styleCommandDescription(a),i),""]));let l=t.visibleArguments(e).map(f=>s(t.styleArgumentTerm(t.argumentTerm(f)),t.styleArgumentDescription(t.argumentDescription(f))));l.length>0&&(o=o.concat([t.styleTitle("Arguments:"),...l,""]));let u=t.visibleOptions(e).map(f=>s(t.styleOptionTerm(t.optionTerm(f)),t.styleOptionDescription(t.optionDescription(f))));if(u.length>0&&(o=o.concat([t.styleTitle("Options:"),...u,""])),t.showGlobalOptions){let f=t.visibleGlobalOptions(e).map(d=>s(t.styleOptionTerm(t.optionTerm(d)),t.styleOptionDescription(t.optionDescription(d))));f.length>0&&(o=o.concat([t.styleTitle("Global Options:"),...f,""]))}let c=t.visibleCommands(e).map(f=>s(t.styleSubcommandTerm(t.subcommandTerm(f)),t.styleSubcommandDescription(t.subcommandDescription(f))));return c.length>0&&(o=o.concat([t.styleTitle("Commands:"),...c,""])),o.join(`
5
- `)}displayWidth(e){return Qn(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 o=" ".repeat(2);if(!n)return o+e;let a=e.padEnd(t+e.length-i.displayWidth(e)),l=2,c=(this.helpWidth??80)-t-l-2,f;return c<this.minWidthToWrap||i.preformatted(n)?f=n:f=i.boxWrap(n,c).replace(/\n/g,`
6
- `+" ".repeat(t+l)),o+a+" ".repeat(l)+f.replace(/\n/g,`
7
- ${o}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let n=e.split(/\r\n|\n/),i=/[\s]*[^\s]+/g,s=[];return n.forEach(o=>{let a=o.match(i);if(a===null){s.push("");return}let l=[a.shift()],u=this.displayWidth(l[0]);a.forEach(c=>{let f=this.displayWidth(c);if(u+f<=t){l.push(c),u+=f;return}s.push(l.join(""));let d=c.trimStart();l=[d],u=this.displayWidth(d)}),s.push(l.join(""))}),s.join(`
8
- `)}};function Qn(r){let e=/\x1b\[\d*(;\d*)*m/g;return r.replace(e,"")}or.Help=sr;or.stripColor=Qn});var fr=h(ur=>{var{InvalidArgumentError:xc}=De(),lr=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=_c(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 xc(`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?Zn(this.name().replace(/^no-/,"")):Zn(this.name())}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},cr=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,s=i!==void 0?i:!1;return t.negate===(s===e)}};function Zn(r){return r.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function _c(r){let e,t,n=/^-[^-]$/,i=/^--[^-]/,s=r.split(/[ |,]+/).concat("guard");if(n.test(s[0])&&(e=s.shift()),i.test(s[0])&&(t=s.shift()),!e&&n.test(s[0])&&(e=s.shift()),!e&&i.test(s[0])&&(e=t,t=s.shift()),s[0].startsWith("-")){let o=s[0],a=`option creation failed due to '${o}' in option flags '${r}'`;throw/^-[^-][^-]/.test(o)?new Error(`${a}
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,`
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(`
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
+ `+" ".repeat(t+l)),s+a+" ".repeat(l)+m.replace(/\n/g,`
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}
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
- - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):n.test(o)?new Error(`${a}
12
- - too many short flags`):i.test(o)?new Error(`${a}
11
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):n.test(s)?new Error(`${a}
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}}ur.Option=lr;ur.DualOptions=cr});var ti=h(ei=>{function Oc(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 s=1;r[i-1]===e[n-1]?s=0:s=1,t[i][n]=Math.min(t[i-1][n]+1,t[i][n-1]+1,t[i-1][n-1]+s),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 Cc(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(o=>o.slice(2)));let n=[],i=3,s=.4;return e.forEach(o=>{if(o.length<=1)return;let a=Oc(r,o),l=Math.max(r.length,o.length);(l-a)/l>s&&(a<i?(i=a,n=[o]):a===i&&n.push(o))}),n.sort((o,a)=>o.localeCompare(a)),t&&(n=n.map(o=>`--${o}`)),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}}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?`
15
15
  (Did you mean one of ${n.join(", ")}?)`:n.length===1?`
16
- (Did you mean ${n[0]}?)`:""}ei.suggestSimilar=Cc});var si=h(gr=>{var Ac=require("node:events").EventEmitter,mr=require("node:child_process"),ce=require("node:path"),at=require("node:fs"),A=require("node:process"),{Argument:Tc,humanReadableArgName:kc}=ot(),{CommanderError:dr}=De(),{Help:Pc,stripColor:Lc}=ar(),{Option:ri,DualOptions:Ic}=fr(),{suggestSimilar:ni}=ti(),pr=class r extends Ac{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=>A.stdout.write(t),writeErr:t=>A.stderr.write(t),outputError:(t,n)=>n(t),getOutHelpWidth:()=>A.stdout.isTTY?A.stdout.columns:void 0,getErrHelpWidth:()=>A.stderr.isTTY?A.stderr.columns:void 0,getOutHasColors:()=>hr()??(A.stdout.isTTY&&A.stdout.hasColors?.()),getErrHasColors:()=>hr()??(A.stderr.isTTY&&A.stderr.hasColors?.()),stripColor:t=>Lc(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,s=n;typeof i=="object"&&i!==null&&(s=i,i=null),s=s||{};let[,o,a]=e.match(/([^ ]+) *(.*)/),l=this.createCommand(o);return i&&(l.description(i),l._executableHandler=!0),s.isDefault&&(this._defaultCommandName=l._name),l._hidden=!!(s.noHelp||s.hidden),l._executableFile=s.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 Pc,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
- - 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 Tc(e,t)}argument(e,t,n,i){let s=this.createArgument(e,t);return typeof n=="function"?s.default(i).argParser(n):s.default(n),this.addArgument(s),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(/([^ ]+) *(.*)/),s=t??"display help for command",o=this.createCommand(n);return o.helpOption(!1),i&&o.arguments(i),s&&o.description(s),this._addImplicitHelpCommand=!0,this._helpCommand=o,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 dr(e,t,n)),A.exit(e)}action(e){let t=n=>{let i=this.registeredArguments.length,s=n.slice(0,i);return this._storeOptionsAsProperties?s[i]=this:s[i]=this.opts(),s.push(this),e.apply(this,s)};return this._actionHandler=t,this}createOption(e,t){return new ri(e,t)}_callParseArg(e,t,n,i){try{return e.parseArg(t,n)}catch(s){if(s.code==="commander.invalidArgument"){let o=`${i} ${s.message}`;this.error(o,{exitCode:s.exitCode,code:s.code})}throw s}}_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
- - 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("|"),s=t(e).join("|");throw new Error(`cannot add command '${s}' 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 s=e.long.replace(/^--no-/,"--");this._findOption(s)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let i=(s,o,a)=>{s==null&&e.presetArg!==void 0&&(s=e.presetArg);let l=this.getOptionValue(n);s!==null&&e.parseArg?s=this._callParseArg(e,s,l,o):s!==null&&e.variadic&&(s=e._concatValue(s,l)),s==null&&(e.negate?s=!1:e.isBoolean()||e.optional?s=!0:s=""),this.setOptionValueWithSource(n,s,a)};return this.on("option:"+t,s=>{let o=`error: option '${e.flags}' argument '${s}' is invalid.`;i(s,o,"cli")}),e.envVar&&this.on("optionEnv:"+t,s=>{let o=`error: option '${e.flags}' value '${s}' from env '${e.envVar}' is invalid.`;i(s,o,"env")}),this}_optionEx(e,t,n,i,s){if(typeof t=="object"&&t instanceof ri)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(t,n);if(o.makeOptionMandatory(!!e.mandatory),typeof i=="function")o.default(s).argParser(i);else if(i instanceof RegExp){let a=i;i=(l,u)=>{let c=a.exec(l);return c?c[0]:u},o.default(s).argParser(i)}else o.default(i);return this.addOption(o)}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){A.versions?.electron&&(t.from="electron");let i=A.execArgv??[];(i.includes("-e")||i.includes("--eval")||i.includes("-p")||i.includes("--print"))&&(t.from="eval")}e===void 0&&(e=A.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":A.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(at.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",s=`'${e}' does not exist
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
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}'
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
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(s)}_executeSubCommand(e,t){t=t.slice();let n=!1,i=[".js",".ts",".tsx",".mjs",".cjs"];function s(c,f){let d=ce.resolve(c,f);if(at.existsSync(d))return d;if(i.includes(ce.extname(f)))return;let p=i.find(g=>at.existsSync(`${d}${g}`));if(p)return`${d}${p}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let c;try{c=at.realpathSync(this._scriptPath)}catch{c=this._scriptPath}a=ce.resolve(ce.dirname(c),a)}if(a){let c=s(a,o);if(!c&&!e._executableFile&&this._scriptPath){let f=ce.basename(this._scriptPath,ce.extname(this._scriptPath));f!==this._name&&(c=s(a,`${f}-${e._name}`))}o=c||o}n=i.includes(ce.extname(o));let l;A.platform!=="win32"?n?(t.unshift(o),t=ii(A.execArgv).concat(t),l=mr.spawn(A.argv[0],t,{stdio:"inherit"})):l=mr.spawn(o,t,{stdio:"inherit"}):(this._checkForMissingExecutable(o,a,e._name),t.unshift(o),t=ii(A.execArgv).concat(t),l=mr.spawn(A.execPath,t,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(f=>{A.on(f,()=>{l.killed===!1&&l.exitCode===null&&l.kill(f)})});let u=this._exitCallback;l.on("close",c=>{c=c??1,u?u(new dr(c,"commander.executeSubCommandAsync","(close)")):A.exit(c)}),l.on("error",c=>{if(c.code==="ENOENT")this._checkForMissingExecutable(o,a,e._name);else if(c.code==="EACCES")throw new Error(`'${o}' not executable`);if(!u)A.exit(1);else{let f=new dr(1,"commander.executeSubCommandAsync","(error)");f.nestedError=c,u(f)}}),this.runningCommand=l}_dispatchSubcommand(e,t,n){let i=this._findCommand(e);i||this.help({error:!0}),i._prepareForParse();let s;return s=this._chainOrCallSubCommandHook(s,i,"preSubcommand"),s=this._chainOrCall(s,()=>{if(i._executableHandler)this._executeSubCommand(i,t.concat(n));else return i._parseCommand(t,n)}),s}_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,s)=>{let o=i;if(i!==null&&n.parseArg){let a=`error: command-argument value '${i}' is invalid for argument '${n.name()}'.`;o=this._callParseArg(n,i,s,a)}return o};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,i)=>{let s=n.defaultValue;n.variadic?i<this.args.length?(s=this.args.slice(i),n.parseArg&&(s=s.reduce((o,a)=>e(n,a,o),n.defaultValue))):s===void 0&&(s=[]):i<this.args.length&&(s=this.args[i],n.parseArg&&(s=e(n,s,n.defaultValue))),t[i]=s}),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(s=>s._lifeCycleHooks[t]!==void 0).forEach(s=>{s._lifeCycleHooks[t].forEach(o=>{i.push({hookedCommand:s,callback:o})})}),t==="postAction"&&i.reverse(),i.forEach(s=>{n=this._chainOrCall(n,()=>s.callback(s.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let i=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(s=>{i=this._chainOrCall(i,()=>s(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])},s=`command:${this.name()}`;if(this._actionHandler){i(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(s,e,t)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(s))i(),this._processArguments(),this.parent.emit(s,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(s=>n.conflictsWith.includes(s.attributeName()));i&&this._conflictingOption(n,i)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],i=t,s=e.slice();function o(l){return l.length>1&&l[0]==="-"}let a=null;for(;s.length;){let l=s.shift();if(l==="--"){i===n&&i.push(l),i.push(...s);break}if(a&&!o(l)){this.emit(`option:${a.name()}`,l);continue}if(a=null,o(l)){let u=this._findOption(l);if(u){if(u.required){let c=s.shift();c===void 0&&this.optionMissingArgument(u),this.emit(`option:${u.name()}`,c)}else if(u.optional){let c=null;s.length>0&&!o(s[0])&&(c=s.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()}`),s.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(o(l)&&(i=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(l)){t.push(l),s.length>0&&n.push(...s);break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){t.push(l),s.length>0&&t.push(...s);break}else if(this._defaultCommandName){n.push(l),s.length>0&&n.push(...s);break}}if(this._passThroughOptions){i.push(l),s.length>0&&i.push(...s);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=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}
24
24
  `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
25
25
  `):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
26
- `),this.outputHelp({error:!0}));let n=t||{},i=n.exitCode||1,s=n.code||"commander.error";this._exit(i,s,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in A.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()}`,A.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Ic(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=o=>{let a=o.attributeName(),l=this.getOptionValue(a),u=this.options.find(f=>f.negate&&a===f.attributeName()),c=this.options.find(f=>!f.negate&&a===f.attributeName());return u&&(u.presetArg===void 0&&l===!1||u.presetArg!==void 0&&l===u.presetArg)?u:c||o},i=o=>{let a=n(o),l=a.attributeName();return this.getOptionValueSource(l)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},s=`error: ${i(e)} cannot be used with ${i(t)}`;this.error(s,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let i=[],s=this;do{let o=s.createHelp().visibleOptions(s).filter(a=>a.long).map(a=>a.long);i=i.concat(o),s=s.parent}while(s&&!s._enablePositionalOptions);t=ni(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",s=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${n} but got ${e.length}.`;this.error(s,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let i=[];this.createHelp().visibleCommands(this).forEach(s=>{i.push(s.name()),s.alias()&&i.push(s.alias())}),t=ni(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=>kc(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=ce.basename(e,ce.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,s;return t?(n=a=>this._outputConfiguration.writeErr(a),i=this._outputConfiguration.getErrHasColors(),s=this._outputConfiguration.getErrHelpWidth()):(n=a=>this._outputConfiguration.writeOut(a),i=this._outputConfiguration.getOutHasColors(),s=this._outputConfiguration.getOutHelpWidth()),{error:t,write:a=>(i||(a=this._outputConfiguration.stripColor(a)),n(a)),hasColors:i,helpWidth:s}}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(o=>o.emit("beforeAllHelp",i)),this.emit("beforeHelp",i);let s=this.helpInformation({error:n.error});if(t&&(s=t(s),typeof s!="string"&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",i),this._getCommandAndAncestors().forEach(o=>o.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(A.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
- Expecting one of '${n.join("', '")}'`);let i=`${e}Help`;return this.on(i,s=>{let o;typeof t=="function"?o=t({error:s.error,command:s.command}):o=t,o&&s.write(`${o}
29
- `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(i=>t.is(i))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function ii(r){return r.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n="127.0.0.1",i="9229",s;return(s=e.match(/^(--inspect(-brk)?)$/))!==null?t=s[1]:(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=s[1],/^\d+$/.test(s[3])?i=s[3]:n=s[3]):(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=s[1],n=s[3],i=s[4]),t&&i!=="0"?`${t}=${n}:${parseInt(i)+1}`:e})}function hr(){if(A.env.NO_COLOR||A.env.FORCE_COLOR==="0"||A.env.FORCE_COLOR==="false")return!1;if(A.env.FORCE_COLOR||A.env.CLICOLOR_FORCE!==void 0)return!0}gr.Command=pr;gr.useColor=hr});var lt=h(Q=>{var{Argument:oi}=ot(),{Command:yr}=si(),{CommanderError:Nc,InvalidArgumentError:ai}=De(),{Help:Mc}=ar(),{Option:li}=fr();Q.program=new yr;Q.createCommand=r=>new yr(r);Q.createOption=(r,e)=>new li(r,e);Q.createArgument=(r,e)=>new oi(r,e);Q.Command=yr;Q.Option=li;Q.Argument=oi;Q.Help=Mc;Q.CommanderError=Nc;Q.InvalidArgumentError=ai;Q.InvalidOptionArgumentError=ai});var Pi=h((dE,ki)=>{function Si(r){return Array.isArray(r)?r:[r]}var Tr="",xi=" ",Cr="\\",ou=/^\s+$/,au=/(?:[^\\]|^)\\$/,lu=/^\\!/,cu=/^\\#/,uu=/\r?\n/g,fu=/^\.*\/|^\.+$/,Ar="/",Ci="node-ignore";typeof Symbol<"u"&&(Ci=Symbol.for("node-ignore"));var _i=Ci,mu=(r,e,t)=>Object.defineProperty(r,e,{value:t}),du=/([0-z])-([0-z])/g,Ai=()=>!1,pu=r=>r.replace(du,(e,t,n)=>t.charCodeAt(0)<=n.charCodeAt(0)?e:Tr),hu=r=>{let{length:e}=r;return r.slice(0,e-e%2)},gu=[[/^\uFEFF/,()=>Tr],[/((?:\\\\)*?)(\\?\s+)$/,(r,e,t)=>e+(t.indexOf("\\")===0?xi:Tr)],[/(\\+?)\s/g,(r,e)=>{let{length:t}=e;return e.slice(0,t-t%2)+xi}],[/[\\$.|*+(){^]/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,()=>Cr],[/\\\\/g,()=>Cr],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(r,e,t,n,i)=>e===Cr?`\\[${t}${hu(n)}${i}`:i==="]"&&n.length%2===0?`[${pu(t)}${n}]`:"[]"],[/(?:[^*])$/,r=>/\/$/.test(r)?`${r}$`:`${r}(?=$|\\/$)`],[/(\^|\\\/)?\\\*$/,(r,e)=>`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`]],Oi=Object.create(null),yu=(r,e)=>{let t=Oi[r];return t||(t=gu.reduce((n,[i,s])=>n.replace(i,s.bind(r)),r),Oi[r]=t),e?new RegExp(t,"i"):new RegExp(t)},Lr=r=>typeof r=="string",Eu=r=>r&&Lr(r)&&!ou.test(r)&&!au.test(r)&&r.indexOf("#")!==0,wu=r=>r.split(uu),kr=class{constructor(e,t,n,i){this.origin=e,this.pattern=t,this.negative=n,this.regex=i}},bu=(r,e)=>{let t=r,n=!1;r.indexOf("!")===0&&(n=!0,r=r.substr(1)),r=r.replace(lu,"!").replace(cu,"#");let i=yu(r,e);return new kr(t,r,n,i)},Ru=(r,e)=>{throw new e(r)},ue=(r,e,t)=>Lr(r)?r?ue.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),Ti=r=>fu.test(r);ue.isNotRelative=Ti;ue.convert=r=>r;var Pr=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:n=!1}={}){mu(this,_i,!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[_i]){this._rules=this._rules.concat(e._rules),this._added=!0;return}if(Eu(e)){let t=bu(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,Si(Lr(e)?wu(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(s=>{let{negative:o}=s;if(i===o&&n!==i||o&&!n&&!i&&!t)return;s.regex.test(e)&&(n=!o,i=o)}),{ignored:n,unignored:i}}_test(e,t,n,i){let s=e&&ue.convert(e);return ue(s,e,this._allowRelativePaths?Ai:Ru),this._t(s,t,n,i)}_t(e,t,n,i){if(e in t)return t[e];if(i||(i=e.split(Ar)),i.pop(),!i.length)return t[e]=this._testOne(e,n);let s=this._t(i.join(Ar)+Ar,t,n,i);return t[e]=s.ignored?s:this._testOne(e,n)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return Si(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},gt=r=>new Pr(r),$u=r=>ue(r&&ue.convert(r),r,Ai);gt.isPathValid=$u;gt.default=gt;ki.exports=gt;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,"/");ue.convert=r;let e=/^[a-z]:\//i;ue.isNotRelative=t=>e.test(t)||Ti(t)}});var Oe=h((Ur,Hi)=>{var Et=require("buffer"),oe=Et.Buffer;function Gi(r,e){for(var t in r)e[t]=r[t]}oe.from&&oe.alloc&&oe.allocUnsafe&&oe.allocUnsafeSlow?Hi.exports=Et:(Gi(Et,Ur),Ur.Buffer=Re);function Re(r,e,t){return oe(r,e,t)}Re.prototype=Object.create(oe.prototype);Gi(oe,Re);Re.from=function(r,e,t){if(typeof r=="number")throw new TypeError("Argument must not be a number");return oe(r,e,t)};Re.alloc=function(r,e,t){if(typeof r!="number")throw new TypeError("Argument must be a number");var n=oe(r);return e!==void 0?typeof t=="string"?n.fill(e,t):n.fill(e):n.fill(0),n};Re.allocUnsafe=function(r){if(typeof r!="number")throw new TypeError("Argument must be a number");return oe(r)};Re.allocUnsafeSlow=function(r){if(typeof r!="number")throw new TypeError("Argument must be a number");return Et.SlowBuffer(r)}});var jr=h((kE,Wi)=>{var wt=Oe().Buffer,Mu=require("stream"),Du=require("util");function bt(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+")")}Du.inherits(bt,Mu);bt.prototype.write=function(e){this.buffer=wt.concat([this.buffer,wt.from(e)]),this.emit("data",e)};bt.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};Wi.exports=bt});var Yi=h((PE,Bi)=>{"use strict";function qr(r){var e=(r/8|0)+(r%8===0?0:1);return e}var Fu={ES256:qr(256),ES384:qr(384),ES512:qr(521)};function Uu(r){var e=Fu[r];if(e)return e;throw new Error('Unknown algorithm "'+r+'"')}Bi.exports=Uu});var es=h((LE,Zi)=>{"use strict";var Rt=Oe().Buffer,zi=Yi(),$t=128,Ji=0,ju=32,qu=16,Vu=2,Ki=qu|ju|Ji<<6,vt=Vu|Ji<<6;function Gu(r){return r.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Qi(r){if(Rt.isBuffer(r))return r;if(typeof r=="string")return Rt.from(r,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function Hu(r,e){r=Qi(r);var t=zi(e),n=t+1,i=r.length,s=0;if(r[s++]!==Ki)throw new Error('Could not find expected "seq"');var o=r[s++];if(o===($t|1)&&(o=r[s++]),i-s<o)throw new Error('"seq" specified length of "'+o+'", only "'+(i-s)+'" remaining');if(r[s++]!==vt)throw new Error('Could not find expected "int" for "r"');var a=r[s++];if(i-s-2<a)throw new Error('"r" specified length of "'+a+'", only "'+(i-s-2)+'" available');if(n<a)throw new Error('"r" specified length of "'+a+'", max of "'+n+'" is acceptable');var l=s;if(s+=a,r[s++]!==vt)throw new Error('Could not find expected "int" for "s"');var u=r[s++];if(i-s!==u)throw new Error('"s" specified length of "'+u+'", expected "'+(i-s)+'"');if(n<u)throw new Error('"s" specified length of "'+u+'", max of "'+n+'" is acceptable');var c=s;if(s+=u,s!==i)throw new Error('Expected to consume entire buffer, but "'+(i-s)+'" bytes remain');var f=t-a,d=t-u,p=Rt.allocUnsafe(f+a+d+u);for(s=0;s<f;++s)p[s]=0;r.copy(p,s,l+Math.max(-f,0),l+a),s=t;for(var g=s;s<g+d;++s)p[s]=0;return r.copy(p,s,c+Math.max(-d,0),c+u),p=p.toString("base64"),p=Gu(p),p}function Xi(r,e,t){for(var n=0;e+n<t&&r[e+n]===0;)++n;var i=r[e+n]>=$t;return i&&--n,n}function Wu(r,e){r=Qi(r);var t=zi(e),n=r.length;if(n!==t*2)throw new TypeError('"'+e+'" signatures must be "'+t*2+'" bytes, saw "'+n+'"');var i=Xi(r,0,t),s=Xi(r,t,r.length),o=t-i,a=t-s,l=2+o+1+1+a,u=l<$t,c=Rt.allocUnsafe((u?2:3)+l),f=0;return c[f++]=Ki,u?c[f++]=l:(c[f++]=$t|1,c[f++]=l&255),c[f++]=vt,c[f++]=o,i<0?(c[f++]=0,f+=r.copy(c,f,0,t)):f+=r.copy(c,f,i,t),c[f++]=vt,c[f++]=a,s<0?(c[f++]=0,r.copy(c,f,t)):r.copy(c,f,t+s),c}Zi.exports={derToJose:Hu,joseToDer:Wu}});var rs=h((IE,ts)=>{"use strict";var qe=require("buffer").Buffer,Vr=require("buffer").SlowBuffer;ts.exports=St;function St(r,e){if(!qe.isBuffer(r)||!qe.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(){qe.prototype.equal=Vr.prototype.equal=function(e){return St(this,e)}};var Bu=qe.prototype.equal,Yu=Vr.prototype.equal;St.restore=function(){qe.prototype.equal=Bu,Vr.prototype.equal=Yu}});var Br=h((NE,fs)=>{var Ae=Oe().Buffer,Z=require("crypto"),is=es(),ns=require("util"),Xu=`"%s" is not a valid algorithm.
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.
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.
30
30
  Supported algorithms are:
31
- "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,Ve="secret must be a string or buffer",Ce="key must be a string or a buffer",zu="key must be a string, a buffer or an object",Hr=typeof Z.createPublicKey=="function";Hr&&(Ce+=" or a KeyObject",Ve+="or a KeyObject");function ss(r){if(!Ae.isBuffer(r)&&typeof r!="string"&&(!Hr||typeof r!="object"||typeof r.type!="string"||typeof r.asymmetricKeyType!="string"||typeof r.export!="function"))throw ne(Ce)}function os(r){if(!Ae.isBuffer(r)&&typeof r!="string"&&typeof r!="object")throw ne(zu)}function Ju(r){if(!Ae.isBuffer(r)){if(typeof r=="string")return r;if(!Hr||typeof r!="object"||r.type!=="secret"||typeof r.export!="function")throw ne(Ve)}}function Wr(r){return r.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function as(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 ne(r){var e=[].slice.call(arguments,1),t=ns.format.bind(ns,r).apply(null,e);return new TypeError(t)}function Ku(r){return Ae.isBuffer(r)||typeof r=="string"}function Ge(r){return Ku(r)||(r=JSON.stringify(r)),r}function ls(r){return function(t,n){Ju(n),t=Ge(t);var i=Z.createHmac("sha"+r,n),s=(i.update(t),i.digest("base64"));return Wr(s)}}var Gr,Qu="timingSafeEqual"in Z?function(e,t){return e.byteLength!==t.byteLength?!1:Z.timingSafeEqual(e,t)}:function(e,t){return Gr||(Gr=rs()),Gr(e,t)};function Zu(r){return function(t,n,i){var s=ls(r)(t,i);return Qu(Ae.from(n),Ae.from(s))}}function cs(r){return function(t,n){os(n),t=Ge(t);var i=Z.createSign("RSA-SHA"+r),s=(i.update(t),i.sign(n,"base64"));return Wr(s)}}function us(r){return function(t,n,i){ss(i),t=Ge(t),n=as(n);var s=Z.createVerify("RSA-SHA"+r);return s.update(t),s.verify(i,n,"base64")}}function ef(r){return function(t,n){os(n),t=Ge(t);var i=Z.createSign("RSA-SHA"+r),s=(i.update(t),i.sign({key:n,padding:Z.constants.RSA_PKCS1_PSS_PADDING,saltLength:Z.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return Wr(s)}}function tf(r){return function(t,n,i){ss(i),t=Ge(t),n=as(n);var s=Z.createVerify("RSA-SHA"+r);return s.update(t),s.verify({key:i,padding:Z.constants.RSA_PKCS1_PSS_PADDING,saltLength:Z.constants.RSA_PSS_SALTLEN_DIGEST},n,"base64")}}function rf(r){var e=cs(r);return function(){var n=e.apply(null,arguments);return n=is.derToJose(n,"ES"+r),n}}function nf(r){var e=us(r);return function(n,i,s){i=is.joseToDer(i,"ES"+r).toString("base64");var o=e(n,i,s);return o}}function sf(){return function(){return""}}function of(){return function(e,t){return t===""}}fs.exports=function(e){var t={hs:ls,rs:cs,ps:ef,es:rf,none:sf},n={hs:Zu,rs:us,ps:tf,es:nf,none:of},i=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!i)throw ne(Xu,e);var s=(i[1]||i[3]).toLowerCase(),o=i[2];return{sign:t[s](o),verify:n[s](o)}}});var Yr=h((ME,ms)=>{var af=require("buffer").Buffer;ms.exports=function(e){return typeof e=="string"?e:typeof e=="number"||af.isBuffer(e)?e.toString():JSON.stringify(e)}});var Es=h((DE,ys)=>{var lf=Oe().Buffer,ds=jr(),cf=Br(),uf=require("stream"),ps=Yr(),Xr=require("util");function hs(r,e){return lf.from(r,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function ff(r,e,t){t=t||"utf8";var n=hs(ps(r),"binary"),i=hs(ps(e),t);return Xr.format("%s.%s",n,i)}function gs(r){var e=r.header,t=r.payload,n=r.secret||r.privateKey,i=r.encoding,s=cf(e.alg),o=ff(e,t,i),a=s.sign(o,n);return Xr.format("%s.%s",o,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 ds(e);this.readable=!0,this.header=r.header,this.encoding=r.encoding,this.secret=this.privateKey=this.key=t,this.payload=new ds(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))}Xr.inherits(xt,uf);xt.prototype.sign=function(){try{var e=gs({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=gs;ys.exports=xt});var Cs=h((FE,Os)=>{var bs=Oe().Buffer,ws=jr(),mf=Br(),df=require("stream"),Rs=Yr(),pf=require("util"),hf=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function gf(r){return Object.prototype.toString.call(r)==="[object Object]"}function yf(r){if(gf(r))return r;try{return JSON.parse(r)}catch{return}}function $s(r){var e=r.split(".",1)[0];return yf(bs.from(e,"base64").toString("binary"))}function Ef(r){return r.split(".",2).join(".")}function vs(r){return r.split(".")[2]}function wf(r,e){e=e||"utf8";var t=r.split(".")[1];return bs.from(t,"base64").toString(e)}function Ss(r){return hf.test(r)&&!!$s(r)}function xs(r,e,t){if(!e){var n=new Error("Missing algorithm parameter for jws.verify");throw n.code="MISSING_ALGORITHM",n}r=Rs(r);var i=vs(r),s=Ef(r),o=mf(e);return o.verify(s,i,t)}function _s(r,e){if(e=e||{},r=Rs(r),!Ss(r))return null;var t=$s(r);if(!t)return null;var n=wf(r);return(t.typ==="JWT"||e.json)&&(n=JSON.parse(n,e.encoding)),{header:t,payload:n,signature:vs(r)}}function Te(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 ws(e);this.readable=!0,this.algorithm=r.algorithm,this.encoding=r.encoding,this.secret=this.publicKey=this.key=t,this.signature=new ws(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))}pf.inherits(Te,df);Te.prototype.verify=function(){try{var e=xs(this.signature.buffer,this.algorithm,this.key.buffer),t=_s(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")}};Te.decode=_s;Te.isValid=Ss;Te.verify=xs;Os.exports=Te});var Ot=h(he=>{var As=Es(),_t=Cs(),bf=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];he.ALGORITHMS=bf;he.sign=As.sign;he.verify=_t.verify;he.decode=_t.decode;he.isValid=_t.isValid;he.createSign=function(e){return new As(e)};he.createVerify=function(e){return new _t(e)}});var zr=h((jE,Ts)=>{var Rf=Ot();Ts.exports=function(r,e){e=e||{};var t=Rf.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 He=h((qE,ks)=>{var Ct=function(r,e){Error.call(this,r),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name="JsonWebTokenError",this.message=r,e&&(this.inner=e)};Ct.prototype=Object.create(Error.prototype);Ct.prototype.constructor=Ct;ks.exports=Ct});var Jr=h((VE,Ls)=>{var Ps=He(),At=function(r,e){Ps.call(this,r),this.name="NotBeforeError",this.date=e};At.prototype=Object.create(Ps.prototype);At.prototype.constructor=At;Ls.exports=At});var Kr=h((GE,Ns)=>{var Is=He(),Tt=function(r,e){Is.call(this,r),this.name="TokenExpiredError",this.expiredAt=e};Tt.prototype=Object.create(Is.prototype);Tt.prototype.constructor=Tt;Ns.exports=Tt});var Ds=h((HE,Ms)=>{var ke=1e3,Pe=ke*60,Le=Pe*60,$e=Le*24,$f=$e*7,vf=$e*365.25;Ms.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return Sf(r);if(t==="number"&&isFinite(r))return e.long?_f(r):xf(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function Sf(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*vf;case"weeks":case"week":case"w":return t*$f;case"days":case"day":case"d":return t*$e;case"hours":case"hour":case"hrs":case"hr":case"h":return t*Le;case"minutes":case"minute":case"mins":case"min":case"m":return t*Pe;case"seconds":case"second":case"secs":case"sec":case"s":return t*ke;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function xf(r){var e=Math.abs(r);return e>=$e?Math.round(r/$e)+"d":e>=Le?Math.round(r/Le)+"h":e>=Pe?Math.round(r/Pe)+"m":e>=ke?Math.round(r/ke)+"s":r+"ms"}function _f(r){var e=Math.abs(r);return e>=$e?kt(r,e,$e,"day"):e>=Le?kt(r,e,Le,"hour"):e>=Pe?kt(r,e,Pe,"minute"):e>=ke?kt(r,e,ke,"second"):r+" ms"}function kt(r,e,t,n){var i=e>=t*1.5;return Math.round(r/t)+" "+n+(i?"s":"")}});var Qr=h((WE,Fs)=>{var Of=Ds();Fs.exports=function(r,e){var t=e||Math.floor(Date.now()/1e3);if(typeof r=="string"){var n=Of(r);return typeof n>"u"?void 0:Math.floor(t+n/1e3)}else return typeof r=="number"?t+r:void 0}});var We=h((BE,Us)=>{"use strict";var Cf="2.0.0",Af=Number.MAX_SAFE_INTEGER||9007199254740991,Tf=16,kf=250,Pf=["major","premajor","minor","preminor","patch","prepatch","prerelease"];Us.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:Tf,MAX_SAFE_BUILD_LENGTH:kf,MAX_SAFE_INTEGER:Af,RELEASE_TYPES:Pf,SEMVER_SPEC_VERSION:Cf,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var Be=h((YE,js)=>{"use strict";var Lf=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{};js.exports=Lf});var Ie=h((ae,qs)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:Zr,MAX_SAFE_BUILD_LENGTH:If,MAX_LENGTH:Nf}=We(),Mf=Be();ae=qs.exports={};var Df=ae.re=[],Ff=ae.safeRe=[],w=ae.src=[],Uf=ae.safeSrc=[],b=ae.t={},jf=0,en="[a-zA-Z0-9-]",qf=[["\\s",1],["\\d",Nf],[en,If]],Vf=r=>{for(let[e,t]of qf)r=r.split(`${e}*`).join(`${e}{0,${t}}`).split(`${e}+`).join(`${e}{1,${t}}`);return r},v=(r,e,t)=>{let n=Vf(e),i=jf++;Mf(r,i,e),b[r]=i,w[i]=e,Uf[i]=n,Df[i]=new RegExp(e,t?"g":void 0),Ff[i]=new RegExp(n,t?"g":void 0)};v("NUMERICIDENTIFIER","0|[1-9]\\d*");v("NUMERICIDENTIFIERLOOSE","\\d+");v("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${en}*`);v("MAINVERSION",`(${w[b.NUMERICIDENTIFIER]})\\.(${w[b.NUMERICIDENTIFIER]})\\.(${w[b.NUMERICIDENTIFIER]})`);v("MAINVERSIONLOOSE",`(${w[b.NUMERICIDENTIFIERLOOSE]})\\.(${w[b.NUMERICIDENTIFIERLOOSE]})\\.(${w[b.NUMERICIDENTIFIERLOOSE]})`);v("PRERELEASEIDENTIFIER",`(?:${w[b.NONNUMERICIDENTIFIER]}|${w[b.NUMERICIDENTIFIER]})`);v("PRERELEASEIDENTIFIERLOOSE",`(?:${w[b.NONNUMERICIDENTIFIER]}|${w[b.NUMERICIDENTIFIERLOOSE]})`);v("PRERELEASE",`(?:-(${w[b.PRERELEASEIDENTIFIER]}(?:\\.${w[b.PRERELEASEIDENTIFIER]})*))`);v("PRERELEASELOOSE",`(?:-?(${w[b.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${w[b.PRERELEASEIDENTIFIERLOOSE]})*))`);v("BUILDIDENTIFIER",`${en}+`);v("BUILD",`(?:\\+(${w[b.BUILDIDENTIFIER]}(?:\\.${w[b.BUILDIDENTIFIER]})*))`);v("FULLPLAIN",`v?${w[b.MAINVERSION]}${w[b.PRERELEASE]}?${w[b.BUILD]}?`);v("FULL",`^${w[b.FULLPLAIN]}$`);v("LOOSEPLAIN",`[v=\\s]*${w[b.MAINVERSIONLOOSE]}${w[b.PRERELEASELOOSE]}?${w[b.BUILD]}?`);v("LOOSE",`^${w[b.LOOSEPLAIN]}$`);v("GTLT","((?:<|>)?=?)");v("XRANGEIDENTIFIERLOOSE",`${w[b.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);v("XRANGEIDENTIFIER",`${w[b.NUMERICIDENTIFIER]}|x|X|\\*`);v("XRANGEPLAIN",`[v=\\s]*(${w[b.XRANGEIDENTIFIER]})(?:\\.(${w[b.XRANGEIDENTIFIER]})(?:\\.(${w[b.XRANGEIDENTIFIER]})(?:${w[b.PRERELEASE]})?${w[b.BUILD]}?)?)?`);v("XRANGEPLAINLOOSE",`[v=\\s]*(${w[b.XRANGEIDENTIFIERLOOSE]})(?:\\.(${w[b.XRANGEIDENTIFIERLOOSE]})(?:\\.(${w[b.XRANGEIDENTIFIERLOOSE]})(?:${w[b.PRERELEASELOOSE]})?${w[b.BUILD]}?)?)?`);v("XRANGE",`^${w[b.GTLT]}\\s*${w[b.XRANGEPLAIN]}$`);v("XRANGELOOSE",`^${w[b.GTLT]}\\s*${w[b.XRANGEPLAINLOOSE]}$`);v("COERCEPLAIN",`(^|[^\\d])(\\d{1,${Zr}})(?:\\.(\\d{1,${Zr}}))?(?:\\.(\\d{1,${Zr}}))?`);v("COERCE",`${w[b.COERCEPLAIN]}(?:$|[^\\d])`);v("COERCEFULL",w[b.COERCEPLAIN]+`(?:${w[b.PRERELEASE]})?(?:${w[b.BUILD]})?(?:$|[^\\d])`);v("COERCERTL",w[b.COERCE],!0);v("COERCERTLFULL",w[b.COERCEFULL],!0);v("LONETILDE","(?:~>?)");v("TILDETRIM",`(\\s*)${w[b.LONETILDE]}\\s+`,!0);ae.tildeTrimReplace="$1~";v("TILDE",`^${w[b.LONETILDE]}${w[b.XRANGEPLAIN]}$`);v("TILDELOOSE",`^${w[b.LONETILDE]}${w[b.XRANGEPLAINLOOSE]}$`);v("LONECARET","(?:\\^)");v("CARETTRIM",`(\\s*)${w[b.LONECARET]}\\s+`,!0);ae.caretTrimReplace="$1^";v("CARET",`^${w[b.LONECARET]}${w[b.XRANGEPLAIN]}$`);v("CARETLOOSE",`^${w[b.LONECARET]}${w[b.XRANGEPLAINLOOSE]}$`);v("COMPARATORLOOSE",`^${w[b.GTLT]}\\s*(${w[b.LOOSEPLAIN]})$|^$`);v("COMPARATOR",`^${w[b.GTLT]}\\s*(${w[b.FULLPLAIN]})$|^$`);v("COMPARATORTRIM",`(\\s*)${w[b.GTLT]}\\s*(${w[b.LOOSEPLAIN]}|${w[b.XRANGEPLAIN]})`,!0);ae.comparatorTrimReplace="$1$2$3";v("HYPHENRANGE",`^\\s*(${w[b.XRANGEPLAIN]})\\s+-\\s+(${w[b.XRANGEPLAIN]})\\s*$`);v("HYPHENRANGELOOSE",`^\\s*(${w[b.XRANGEPLAINLOOSE]})\\s+-\\s+(${w[b.XRANGEPLAINLOOSE]})\\s*$`);v("STAR","(<|>)?=?\\s*\\*");v("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");v("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var Pt=h((XE,Vs)=>{"use strict";var Gf=Object.freeze({loose:!0}),Hf=Object.freeze({}),Wf=r=>r?typeof r!="object"?Gf:r:Hf;Vs.exports=Wf});var tn=h((zE,Ws)=>{"use strict";var Gs=/^[0-9]+$/,Hs=(r,e)=>{if(typeof r=="number"&&typeof e=="number")return r===e?0:r<e?-1:1;let t=Gs.test(r),n=Gs.test(e);return t&&n&&(r=+r,e=+e),r===e?0:t&&!n?-1:n&&!t?1:r<e?-1:1},Bf=(r,e)=>Hs(e,r);Ws.exports={compareIdentifiers:Hs,rcompareIdentifiers:Bf}});var H=h((JE,Ys)=>{"use strict";var Lt=Be(),{MAX_LENGTH:Bs,MAX_SAFE_INTEGER:It}=We(),{safeRe:Nt,t:Mt}=Ie(),Yf=Pt(),{compareIdentifiers:rn}=tn(),nn=class r{constructor(e,t){if(t=Yf(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>Bs)throw new TypeError(`version is longer than ${Bs} characters`);Lt("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;let n=e.trim().match(t.loose?Nt[Mt.LOOSE]:Nt[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>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 s=+i;if(s>=0&&s<It)return s}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 rn(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 rn(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?Nt[Mt.PRERELEASELOOSE]:Nt[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 s=this.prerelease.length;for(;--s>=0;)typeof this.prerelease[s]=="number"&&(this.prerelease[s]++,s=-2);if(s===-1){if(t===this.prerelease.join(".")&&n===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(i)}}if(t){let s=[t,i];n===!1&&(s=[t]),rn(this.prerelease[0],t)===0?isNaN(this.prerelease[1])&&(this.prerelease=s):this.prerelease=s}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};Ys.exports=nn});var ve=h((KE,zs)=>{"use strict";var Xs=H(),Xf=(r,e,t=!1)=>{if(r instanceof Xs)return r;try{return new Xs(r,e)}catch(n){if(!t)return null;throw n}};zs.exports=Xf});var Ks=h((QE,Js)=>{"use strict";var zf=ve(),Jf=(r,e)=>{let t=zf(r,e);return t?t.version:null};Js.exports=Jf});var Zs=h((ZE,Qs)=>{"use strict";var Kf=ve(),Qf=(r,e)=>{let t=Kf(r.trim().replace(/^[=v]+/,""),e);return t?t.version:null};Qs.exports=Qf});var ro=h((ew,to)=>{"use strict";var eo=H(),Zf=(r,e,t,n,i)=>{typeof t=="string"&&(i=n,n=t,t=void 0);try{return new eo(r instanceof eo?r.version:r,t).inc(e,n,i).version}catch{return null}};to.exports=Zf});var so=h((tw,io)=>{"use strict";var no=ve(),em=(r,e)=>{let t=no(r,null,!0),n=no(e,null,!0),i=t.compare(n);if(i===0)return null;let s=i>0,o=s?t:n,a=s?n:t,l=!!o.prerelease.length;if(!!a.prerelease.length&&!l){if(!a.patch&&!a.minor)return"major";if(a.compareMain(o)===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"};io.exports=em});var ao=h((rw,oo)=>{"use strict";var tm=H(),rm=(r,e)=>new tm(r,e).major;oo.exports=rm});var co=h((nw,lo)=>{"use strict";var nm=H(),im=(r,e)=>new nm(r,e).minor;lo.exports=im});var fo=h((iw,uo)=>{"use strict";var sm=H(),om=(r,e)=>new sm(r,e).patch;uo.exports=om});var po=h((sw,mo)=>{"use strict";var am=ve(),lm=(r,e)=>{let t=am(r,e);return t&&t.prerelease.length?t.prerelease:null};mo.exports=lm});var ee=h((ow,go)=>{"use strict";var ho=H(),cm=(r,e,t)=>new ho(r,t).compare(new ho(e,t));go.exports=cm});var Eo=h((aw,yo)=>{"use strict";var um=ee(),fm=(r,e,t)=>um(e,r,t);yo.exports=fm});var bo=h((lw,wo)=>{"use strict";var mm=ee(),dm=(r,e)=>mm(r,e,!0);wo.exports=dm});var Dt=h((cw,$o)=>{"use strict";var Ro=H(),pm=(r,e,t)=>{let n=new Ro(r,t),i=new Ro(e,t);return n.compare(i)||n.compareBuild(i)};$o.exports=pm});var So=h((uw,vo)=>{"use strict";var hm=Dt(),gm=(r,e)=>r.sort((t,n)=>hm(t,n,e));vo.exports=gm});var _o=h((fw,xo)=>{"use strict";var ym=Dt(),Em=(r,e)=>r.sort((t,n)=>ym(n,t,e));xo.exports=Em});var Ye=h((mw,Oo)=>{"use strict";var wm=ee(),bm=(r,e,t)=>wm(r,e,t)>0;Oo.exports=bm});var Ft=h((dw,Co)=>{"use strict";var Rm=ee(),$m=(r,e,t)=>Rm(r,e,t)<0;Co.exports=$m});var sn=h((pw,Ao)=>{"use strict";var vm=ee(),Sm=(r,e,t)=>vm(r,e,t)===0;Ao.exports=Sm});var on=h((hw,To)=>{"use strict";var xm=ee(),_m=(r,e,t)=>xm(r,e,t)!==0;To.exports=_m});var Ut=h((gw,ko)=>{"use strict";var Om=ee(),Cm=(r,e,t)=>Om(r,e,t)>=0;ko.exports=Cm});var jt=h((yw,Po)=>{"use strict";var Am=ee(),Tm=(r,e,t)=>Am(r,e,t)<=0;Po.exports=Tm});var an=h((Ew,Lo)=>{"use strict";var km=sn(),Pm=on(),Lm=Ye(),Im=Ut(),Nm=Ft(),Mm=jt(),Dm=(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 km(r,t,n);case"!=":return Pm(r,t,n);case">":return Lm(r,t,n);case">=":return Im(r,t,n);case"<":return Nm(r,t,n);case"<=":return Mm(r,t,n);default:throw new TypeError(`Invalid operator: ${e}`)}};Lo.exports=Dm});var No=h((ww,Io)=>{"use strict";var Fm=H(),Um=ve(),{safeRe:qt,t:Vt}=Ie(),jm=(r,e)=>{if(r instanceof Fm)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[Vt.COERCEFULL]:qt[Vt.COERCE]);else{let l=e.includePrerelease?qt[Vt.COERCERTLFULL]:qt[Vt.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",s=t[4]||"0",o=e.includePrerelease&&t[5]?`-${t[5]}`:"",a=e.includePrerelease&&t[6]?`+${t[6]}`:"";return Um(`${n}.${i}.${s}${o}${a}`,e)};Io.exports=jm});var Do=h((bw,Mo)=>{"use strict";var ln=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}};Mo.exports=ln});var te=h((Rw,qo)=>{"use strict";var qm=/\s+/g,cn=class r{constructor(e,t){if(t=Gm(t),e instanceof r)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new r(e.raw,t);if(e instanceof un)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(qm," "),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=>!Uo(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&&Jm(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&&Xm)|(this.options.loose&&zm))+":"+e,i=Fo.get(n);if(i)return i;let s=this.options.loose,o=s?Y[W.HYPHENRANGELOOSE]:Y[W.HYPHENRANGE];e=e.replace(o,od(this.options.includePrerelease)),I("hyphen replace",e),e=e.replace(Y[W.COMPARATORTRIM],Wm),I("comparator trim",e),e=e.replace(Y[W.TILDETRIM],Bm),I("tilde trim",e),e=e.replace(Y[W.CARETTRIM],Ym),I("caret trim",e);let a=e.split(" ").map(f=>Km(f,this.options)).join(" ").split(/\s+/).map(f=>sd(f,this.options));s&&(a=a.filter(f=>(I("loose invalid filter",f,this.options),!!f.match(Y[W.COMPARATORLOOSE])))),I("range list",a);let l=new Map,u=a.map(f=>new un(f,this.options));for(let f of u){if(Uo(f))return[f];l.set(f.value,f)}l.size>1&&l.has("")&&l.delete("");let c=[...l.values()];return Fo.set(n,c),c}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Range is required");return this.set.some(n=>jo(n,t)&&e.set.some(i=>jo(i,t)&&n.every(s=>i.every(o=>s.intersects(o,t)))))}test(e){if(!e)return!1;if(typeof e=="string")try{e=new Hm(e,this.options)}catch{return!1}for(let t=0;t<this.set.length;t++)if(ad(this.set[t],e,this.options))return!0;return!1}};qo.exports=cn;var Vm=Do(),Fo=new Vm,Gm=Pt(),un=Xe(),I=Be(),Hm=H(),{safeRe:Y,t:W,comparatorTrimReplace:Wm,tildeTrimReplace:Bm,caretTrimReplace:Ym}=Ie(),{FLAG_INCLUDE_PRERELEASE:Xm,FLAG_LOOSE:zm}=We(),Uo=r=>r.value==="<0.0.0-0",Jm=r=>r.value==="",jo=(r,e)=>{let t=!0,n=r.slice(),i=n.pop();for(;t&&n.length;)t=n.every(s=>i.intersects(s,e)),i=n.pop();return t},Km=(r,e)=>(r=r.replace(Y[W.BUILD],""),I("comp",r,e),r=ed(r,e),I("caret",r),r=Qm(r,e),I("tildes",r),r=rd(r,e),I("xrange",r),r=id(r,e),I("stars",r),r),X=r=>!r||r.toLowerCase()==="x"||r==="*",Qm=(r,e)=>r.trim().split(/\s+/).map(t=>Zm(t,e)).join(" "),Zm=(r,e)=>{let t=e.loose?Y[W.TILDELOOSE]:Y[W.TILDE];return r.replace(t,(n,i,s,o,a)=>{I("tilde",r,n,i,s,o,a);let l;return X(i)?l="":X(s)?l=`>=${i}.0.0 <${+i+1}.0.0-0`:X(o)?l=`>=${i}.${s}.0 <${i}.${+s+1}.0-0`:a?(I("replaceTilde pr",a),l=`>=${i}.${s}.${o}-${a} <${i}.${+s+1}.0-0`):l=`>=${i}.${s}.${o} <${i}.${+s+1}.0-0`,I("tilde return",l),l})},ed=(r,e)=>r.trim().split(/\s+/).map(t=>td(t,e)).join(" "),td=(r,e)=>{I("caret",r,e);let t=e.loose?Y[W.CARETLOOSE]:Y[W.CARET],n=e.includePrerelease?"-0":"";return r.replace(t,(i,s,o,a,l)=>{I("caret",r,i,s,o,a,l);let u;return X(s)?u="":X(o)?u=`>=${s}.0.0${n} <${+s+1}.0.0-0`:X(a)?s==="0"?u=`>=${s}.${o}.0${n} <${s}.${+o+1}.0-0`:u=`>=${s}.${o}.0${n} <${+s+1}.0.0-0`:l?(I("replaceCaret pr",l),s==="0"?o==="0"?u=`>=${s}.${o}.${a}-${l} <${s}.${o}.${+a+1}-0`:u=`>=${s}.${o}.${a}-${l} <${s}.${+o+1}.0-0`:u=`>=${s}.${o}.${a}-${l} <${+s+1}.0.0-0`):(I("no pr"),s==="0"?o==="0"?u=`>=${s}.${o}.${a}${n} <${s}.${o}.${+a+1}-0`:u=`>=${s}.${o}.${a}${n} <${s}.${+o+1}.0-0`:u=`>=${s}.${o}.${a} <${+s+1}.0.0-0`),I("caret return",u),u})},rd=(r,e)=>(I("replaceXRanges",r,e),r.split(/\s+/).map(t=>nd(t,e)).join(" ")),nd=(r,e)=>{r=r.trim();let t=e.loose?Y[W.XRANGELOOSE]:Y[W.XRANGE];return r.replace(t,(n,i,s,o,a,l)=>{I("xRange",r,n,i,s,o,a,l);let u=X(s),c=u||X(o),f=c||X(a),d=f;return i==="="&&d&&(i=""),l=e.includePrerelease?"-0":"",u?i===">"||i==="<"?n="<0.0.0-0":n="*":i&&d?(c&&(o=0),a=0,i===">"?(i=">=",c?(s=+s+1,o=0,a=0):(o=+o+1,a=0)):i==="<="&&(i="<",c?s=+s+1:o=+o+1),i==="<"&&(l="-0"),n=`${i+s}.${o}.${a}${l}`):c?n=`>=${s}.0.0${l} <${+s+1}.0.0-0`:f&&(n=`>=${s}.${o}.0${l} <${s}.${+o+1}.0-0`),I("xRange return",n),n})},id=(r,e)=>(I("replaceStars",r,e),r.trim().replace(Y[W.STAR],"")),sd=(r,e)=>(I("replaceGTE0",r,e),r.trim().replace(Y[e.includePrerelease?W.GTE0PRE:W.GTE0],"")),od=r=>(e,t,n,i,s,o,a,l,u,c,f,d)=>(X(n)?t="":X(i)?t=`>=${n}.0.0${r?"-0":""}`:X(s)?t=`>=${n}.${i}.0${r?"-0":""}`:o?t=`>=${t}`:t=`>=${t}${r?"-0":""}`,X(u)?l="":X(c)?l=`<${+u+1}.0.0-0`:X(f)?l=`<${u}.${+c+1}.0-0`:d?l=`<=${u}.${c}.${f}-${d}`:r?l=`<${u}.${c}.${+f+1}-0`:l=`<=${l}`,`${t} ${l}`.trim()),ad=(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!==un.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 Xe=h(($w,Yo)=>{"use strict";var ze=Symbol("SemVer ANY"),dn=class r{static get ANY(){return ze}constructor(e,t){if(t=Vo(t),e instanceof r){if(e.loose===!!t.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),mn("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,mn("comp",this)}parse(e){let t=this.options.loose?Go[Ho.COMPARATORLOOSE]:Go[Ho.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 Wo(n[2],this.options.loose):this.semver=ze}toString(){return this.value}test(e){if(mn("Comparator.test",e,this.options.loose),this.semver===ze||e===ze)return!0;if(typeof e=="string")try{e=new Wo(e,this.options)}catch{return!1}return fn(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 Bo(e.value,t).test(this.value):e.operator===""?e.value===""?!0:new Bo(this.value,t).test(e.semver):(t=Vo(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("=")||fn(this.semver,"<",e.semver,t)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||fn(this.semver,">",e.semver,t)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};Yo.exports=dn;var Vo=Pt(),{safeRe:Go,t:Ho}=Ie(),fn=an(),mn=Be(),Wo=H(),Bo=te()});var Je=h((vw,Xo)=>{"use strict";var ld=te(),cd=(r,e,t)=>{try{e=new ld(e,t)}catch{return!1}return e.test(r)};Xo.exports=cd});var Jo=h((Sw,zo)=>{"use strict";var ud=te(),fd=(r,e)=>new ud(r,e).set.map(t=>t.map(n=>n.value).join(" ").trim().split(" "));zo.exports=fd});var Qo=h((xw,Ko)=>{"use strict";var md=H(),dd=te(),pd=(r,e,t)=>{let n=null,i=null,s=null;try{s=new dd(e,t)}catch{return null}return r.forEach(o=>{s.test(o)&&(!n||i.compare(o)===-1)&&(n=o,i=new md(n,t))}),n};Ko.exports=pd});var ea=h((_w,Zo)=>{"use strict";var hd=H(),gd=te(),yd=(r,e,t)=>{let n=null,i=null,s=null;try{s=new gd(e,t)}catch{return null}return r.forEach(o=>{s.test(o)&&(!n||i.compare(o)===1)&&(n=o,i=new hd(n,t))}),n};Zo.exports=yd});var na=h((Ow,ra)=>{"use strict";var pn=H(),Ed=te(),ta=Ye(),wd=(r,e)=>{r=new Ed(r,e);let t=new pn("0.0.0");if(r.test(t)||(t=new pn("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],s=null;i.forEach(o=>{let a=new pn(o.semver.version);switch(o.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!s||ta(a,s))&&(s=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${o.operator}`)}}),s&&(!t||ta(t,s))&&(t=s)}return t&&r.test(t)?t:null};ra.exports=wd});var sa=h((Cw,ia)=>{"use strict";var bd=te(),Rd=(r,e)=>{try{return new bd(r,e).range||"*"}catch{return null}};ia.exports=Rd});var Gt=h((Aw,ca)=>{"use strict";var $d=H(),la=Xe(),{ANY:vd}=la,Sd=te(),xd=Je(),oa=Ye(),aa=Ft(),_d=jt(),Od=Ut(),Cd=(r,e,t,n)=>{r=new $d(r,n),e=new Sd(e,n);let i,s,o,a,l;switch(t){case">":i=oa,s=_d,o=aa,a=">",l=">=";break;case"<":i=aa,s=Od,o=oa,a="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(xd(r,e,n))return!1;for(let u=0;u<e.set.length;++u){let c=e.set[u],f=null,d=null;if(c.forEach(p=>{p.semver===vd&&(p=new la(">=0.0.0")),f=f||p,d=d||p,i(p.semver,f.semver,n)?f=p:o(p.semver,d.semver,n)&&(d=p)}),f.operator===a||f.operator===l||(!d.operator||d.operator===a)&&s(r,d.semver))return!1;if(d.operator===l&&o(r,d.semver))return!1}return!0};ca.exports=Cd});var fa=h((Tw,ua)=>{"use strict";var Ad=Gt(),Td=(r,e,t)=>Ad(r,e,">",t);ua.exports=Td});var da=h((kw,ma)=>{"use strict";var kd=Gt(),Pd=(r,e,t)=>kd(r,e,"<",t);ma.exports=Pd});var ga=h((Pw,ha)=>{"use strict";var pa=te(),Ld=(r,e,t)=>(r=new pa(r,t),e=new pa(e,t),r.intersects(e,t));ha.exports=Ld});var Ea=h((Lw,ya)=>{"use strict";var Id=Je(),Nd=ee();ya.exports=(r,e,t)=>{let n=[],i=null,s=null,o=r.sort((c,f)=>Nd(c,f,t));for(let c of o)Id(c,e,t)?(s=c,i||(i=c)):(s&&n.push([i,s]),s=null,i=null);i&&n.push([i,null]);let a=[];for(let[c,f]of n)c===f?a.push(c):!f&&c===o[0]?a.push("*"):f?c===o[0]?a.push(`<=${f}`):a.push(`${c} - ${f}`):a.push(`>=${c}`);let l=a.join(" || "),u=typeof e.raw=="string"?e.raw:String(e);return l.length<u.length?l:e}});var Sa=h((Iw,va)=>{"use strict";var wa=te(),gn=Xe(),{ANY:hn}=gn,Ke=Je(),yn=ee(),Md=(r,e,t={})=>{if(r===e)return!0;r=new wa(r,t),e=new wa(e,t);let n=!1;e:for(let i of r.set){for(let s of e.set){let o=Fd(i,s,t);if(n=n||o!==null,o)continue e}if(n)return!1}return!0},Dd=[new gn(">=0.0.0-0")],ba=[new gn(">=0.0.0")],Fd=(r,e,t)=>{if(r===e)return!0;if(r.length===1&&r[0].semver===hn){if(e.length===1&&e[0].semver===hn)return!0;t.includePrerelease?r=Dd:r=ba}if(e.length===1&&e[0].semver===hn){if(t.includePrerelease)return!0;e=ba}let n=new Set,i,s;for(let p of r)p.operator===">"||p.operator===">="?i=Ra(i,p,t):p.operator==="<"||p.operator==="<="?s=$a(s,p,t):n.add(p.semver);if(n.size>1)return null;let o;if(i&&s){if(o=yn(i.semver,s.semver,t),o>0)return null;if(o===0&&(i.operator!==">="||s.operator!=="<="))return null}for(let p of n){if(i&&!Ke(p,String(i),t)||s&&!Ke(p,String(s),t))return null;for(let g of e)if(!Ke(p,String(g),t))return!1;return!0}let a,l,u,c,f=s&&!t.includePrerelease&&s.semver.prerelease.length?s.semver:!1,d=i&&!t.includePrerelease&&i.semver.prerelease.length?i.semver:!1;f&&f.prerelease.length===1&&s.operator==="<"&&f.prerelease[0]===0&&(f=!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=Ra(i,p,t),a===p&&a!==i)return!1}else if(i.operator===">="&&!Ke(i.semver,String(p),t))return!1}if(s){if(f&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===f.major&&p.semver.minor===f.minor&&p.semver.patch===f.patch&&(f=!1),p.operator==="<"||p.operator==="<="){if(l=$a(s,p,t),l===p&&l!==s)return!1}else if(s.operator==="<="&&!Ke(s.semver,String(p),t))return!1}if(!p.operator&&(s||i)&&o!==0)return!1}return!(i&&u&&!s&&o!==0||s&&c&&!i&&o!==0||d||f)},Ra=(r,e,t)=>{if(!r)return e;let n=yn(r.semver,e.semver,t);return n>0?r:n<0||e.operator===">"&&r.operator===">="?e:r},$a=(r,e,t)=>{if(!r)return e;let n=yn(r.semver,e.semver,t);return n<0?r:n>0||e.operator==="<"&&r.operator==="<="?e:r};va.exports=Md});var Ht=h((Nw,Oa)=>{"use strict";var En=Ie(),xa=We(),Ud=H(),_a=tn(),jd=ve(),qd=Ks(),Vd=Zs(),Gd=ro(),Hd=so(),Wd=ao(),Bd=co(),Yd=fo(),Xd=po(),zd=ee(),Jd=Eo(),Kd=bo(),Qd=Dt(),Zd=So(),ep=_o(),tp=Ye(),rp=Ft(),np=sn(),ip=on(),sp=Ut(),op=jt(),ap=an(),lp=No(),cp=Xe(),up=te(),fp=Je(),mp=Jo(),dp=Qo(),pp=ea(),hp=na(),gp=sa(),yp=Gt(),Ep=fa(),wp=da(),bp=ga(),Rp=Ea(),$p=Sa();Oa.exports={parse:jd,valid:qd,clean:Vd,inc:Gd,diff:Hd,major:Wd,minor:Bd,patch:Yd,prerelease:Xd,compare:zd,rcompare:Jd,compareLoose:Kd,compareBuild:Qd,sort:Zd,rsort:ep,gt:tp,lt:rp,eq:np,neq:ip,gte:sp,lte:op,cmp:ap,coerce:lp,Comparator:cp,Range:up,satisfies:fp,toComparators:mp,maxSatisfying:dp,minSatisfying:pp,minVersion:hp,validRange:gp,outside:yp,gtr:Ep,ltr:wp,intersects:bp,simplifyRange:Rp,subset:$p,SemVer:Ud,re:En.re,src:En.src,tokens:En.t,SEMVER_SPEC_VERSION:xa.SEMVER_SPEC_VERSION,RELEASE_TYPES:xa.RELEASE_TYPES,compareIdentifiers:_a.compareIdentifiers,rcompareIdentifiers:_a.rcompareIdentifiers}});var Aa=h((Mw,Ca)=>{var vp=Ht();Ca.exports=vp.satisfies(process.version,">=15.7.0")});var ka=h((Dw,Ta)=>{var Sp=Ht();Ta.exports=Sp.satisfies(process.version,">=16.9.0")});var wn=h((Fw,Pa)=>{var xp=Aa(),_p=ka(),Op={ec:["ES256","ES384","ES512"],rsa:["RS256","PS256","RS384","PS384","RS512","PS512"],"rsa-pss":["PS256","PS384","PS512"]},Cp={ES256:"prime256v1",ES384:"secp384r1",ES512:"secp521r1"};Pa.exports=function(r,e){if(!r||!e)return;let t=e.asymmetricKeyType;if(!t)return;let n=Op[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(xp)switch(t){case"ec":let i=e.asymmetricKeyDetails.namedCurve,s=Cp[r];if(i!==s)throw new Error(`"alg" parameter "${r}" requires curve "${s}".`);break;case"rsa-pss":if(_p){let o=parseInt(r.slice(-3),10),{hashAlgorithm:a,mgf1HashAlgorithm:l,saltLength:u}=e.asymmetricKeyDetails;if(a!==`sha${o}`||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>o>>3)throw new Error(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${r}.`)}break}}});var bn=h((Uw,La)=>{var Ap=Ht();La.exports=Ap.satisfies(process.version,"^6.12.0 || >=8.0.0")});var Ma=h((jw,Na)=>{var k=He(),Tp=Jr(),Ia=Kr(),kp=zr(),Pp=Qr(),Lp=wn(),Ip=bn(),Np=Ot(),{KeyObject:Mp,createSecretKey:Dp,createPublicKey:Fp}=require("crypto"),Rn=["RS256","RS384","RS512"],Up=["ES256","ES384","ES512"],$n=["RS256","RS384","RS512"],jp=["HS256","HS384","HS512"];Ip&&(Rn.splice(Rn.length,0,"PS256","PS384","PS512"),$n.splice($n.length,0,"PS256","PS384","PS512"));Na.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,f){if(c)throw c;return f},t.clockTimestamp&&typeof t.clockTimestamp!="number")return i(new k("clockTimestamp must be a number"));if(t.nonce!==void 0&&(typeof t.nonce!="string"||t.nonce.trim()===""))return i(new k("nonce must be a non-empty string"));if(t.allowInvalidAsymmetricKeyTypes!==void 0&&typeof t.allowInvalidAsymmetricKeyTypes!="boolean")return i(new k("allowInvalidAsymmetricKeyTypes must be a boolean"));let s=t.clockTimestamp||Math.floor(Date.now()/1e3);if(!r)return i(new k("jwt must be provided"));if(typeof r!="string")return i(new k("jwt must be a string"));let o=r.split(".");if(o.length!==3)return i(new k("jwt malformed"));let a;try{a=kp(r,{complete:!0})}catch(c){return i(c)}if(!a)return i(new k("invalid token"));let l=a.header,u;if(typeof e=="function"){if(!n)return i(new k("verify must be called asynchronous if secret or public key is provided as a callback"));u=e}else u=function(c,f){return f(null,e)};return u(l,function(c,f){if(c)return i(new k("error in secret or public key callback: "+c.message));let d=o[2].trim()!=="";if(!d&&f)return i(new k("jwt signature is required"));if(d&&!f)return i(new k("secret or public key must be provided"));if(!d&&!t.algorithms)return i(new k('please specify "none" in "algorithms" to verify unsigned tokens'));if(f!=null&&!(f instanceof Mp))try{f=Fp(f)}catch{try{f=Dp(typeof f=="string"?Buffer.from(f):f)}catch{return i(new k("secretOrPublicKey is not valid key material"))}}if(t.algorithms||(f.type==="secret"?t.algorithms=jp:["rsa","rsa-pss"].includes(f.asymmetricKeyType)?t.algorithms=$n:f.asymmetricKeyType==="ec"?t.algorithms=Up:t.algorithms=Rn),t.algorithms.indexOf(a.header.alg)===-1)return i(new k("invalid algorithm"));if(l.alg.startsWith("HS")&&f.type!=="secret")return i(new k(`secretOrPublicKey must be a symmetric key when using ${l.alg}`));if(/^(?:RS|PS|ES)/.test(l.alg)&&f.type!=="public")return i(new k(`secretOrPublicKey must be an asymmetric key when using ${l.alg}`));if(!t.allowInvalidAsymmetricKeyTypes)try{Lp(l.alg,f)}catch(S){return i(S)}let p;try{p=Np.verify(r,a.header.alg,f)}catch(S){return i(S)}if(!p)return i(new k("invalid signature"));let g=a.payload;if(typeof g.nbf<"u"&&!t.ignoreNotBefore){if(typeof g.nbf!="number")return i(new k("invalid nbf value"));if(g.nbf>s+(t.clockTolerance||0))return i(new Tp("jwt not active",new Date(g.nbf*1e3)))}if(typeof g.exp<"u"&&!t.ignoreExpiration){if(typeof g.exp!="number")return i(new k("invalid exp value"));if(s>=g.exp+(t.clockTolerance||0))return i(new Ia("jwt expired",new Date(g.exp*1e3)))}if(t.audience){let S=Array.isArray(t.audience)?t.audience:[t.audience];if(!(Array.isArray(g.aud)?g.aud:[g.aud]).some(function(R){return S.some(function($){return $ instanceof RegExp?$.test(R):$===R})}))return i(new k("jwt audience invalid. expected: "+S.join(" or ")))}if(t.issuer&&(typeof t.issuer=="string"&&g.iss!==t.issuer||Array.isArray(t.issuer)&&t.issuer.indexOf(g.iss)===-1))return i(new k("jwt issuer invalid. expected: "+t.issuer));if(t.subject&&g.sub!==t.subject)return i(new k("jwt subject invalid. expected: "+t.subject));if(t.jwtid&&g.jti!==t.jwtid)return i(new k("jwt jwtid invalid. expected: "+t.jwtid));if(t.nonce&&g.nonce!==t.nonce)return i(new k("jwt nonce invalid. expected: "+t.nonce));if(t.maxAge){if(typeof g.iat!="number")return i(new k("iat required when maxAge is specified"));let S=Pp(t.maxAge,g.iat);if(typeof S>"u")return i(new k('"maxAge" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'));if(s>=S+(t.clockTolerance||0))return i(new Ia("maxAge exceeded",new Date(S*1e3)))}if(t.complete===!0){let S=a.signature;return i(null,{header:l,payload:g,signature:S})}return i(null,g)})}});var Va=h((qw,qa)=>{var Da=1/0,Ua=9007199254740991,qp=17976931348623157e292,Fa=NaN,Vp="[object Arguments]",Gp="[object Function]",Hp="[object GeneratorFunction]",Wp="[object String]",Bp="[object Symbol]",Yp=/^\s+|\s+$/g,Xp=/^[-+]0x[0-9a-f]+$/i,zp=/^0b[01]+$/i,Jp=/^0o[0-7]+$/i,Kp=/^(?:0|[1-9]\d*)$/,Qp=parseInt;function Zp(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 eh(r,e,t,n){for(var i=r.length,s=t+(n?1:-1);n?s--:++s<i;)if(e(r[s],s,r))return s;return-1}function th(r,e,t){if(e!==e)return eh(r,rh,t);for(var n=t-1,i=r.length;++n<i;)if(r[n]===e)return n;return-1}function rh(r){return r!==r}function nh(r,e){for(var t=-1,n=Array(r);++t<r;)n[t]=e(t);return n}function ih(r,e){return Zp(e,function(t){return r[t]})}function sh(r,e){return function(t){return r(e(t))}}var Wt=Object.prototype,Sn=Wt.hasOwnProperty,Bt=Wt.toString,oh=Wt.propertyIsEnumerable,ah=sh(Object.keys,Object),lh=Math.max;function ch(r,e){var t=ja(r)||ph(r)?nh(r.length,String):[],n=t.length,i=!!n;for(var s in r)(e||Sn.call(r,s))&&!(i&&(s=="length"||fh(s,n)))&&t.push(s);return t}function uh(r){if(!mh(r))return ah(r);var e=[];for(var t in Object(r))Sn.call(r,t)&&t!="constructor"&&e.push(t);return e}function fh(r,e){return e=e??Ua,!!e&&(typeof r=="number"||Kp.test(r))&&r>-1&&r%1==0&&r<e}function mh(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||Wt;return r===t}function dh(r,e,t,n){r=xn(r)?r:Sh(r),t=t&&!n?Rh(t):0;var i=r.length;return t<0&&(t=lh(i+t,0)),Eh(r)?t<=i&&r.indexOf(e,t)>-1:!!i&&th(r,e,t)>-1}function ph(r){return hh(r)&&Sn.call(r,"callee")&&(!oh.call(r,"callee")||Bt.call(r)==Vp)}var ja=Array.isArray;function xn(r){return r!=null&&yh(r.length)&&!gh(r)}function hh(r){return _n(r)&&xn(r)}function gh(r){var e=vn(r)?Bt.call(r):"";return e==Gp||e==Hp}function yh(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=Ua}function vn(r){var e=typeof r;return!!r&&(e=="object"||e=="function")}function _n(r){return!!r&&typeof r=="object"}function Eh(r){return typeof r=="string"||!ja(r)&&_n(r)&&Bt.call(r)==Wp}function wh(r){return typeof r=="symbol"||_n(r)&&Bt.call(r)==Bp}function bh(r){if(!r)return r===0?r:0;if(r=$h(r),r===Da||r===-Da){var e=r<0?-1:1;return e*qp}return r===r?r:0}function Rh(r){var e=bh(r),t=e%1;return e===e?t?e-t:e:0}function $h(r){if(typeof r=="number")return r;if(wh(r))return Fa;if(vn(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=vn(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=r.replace(Yp,"");var t=zp.test(r);return t||Jp.test(r)?Qp(r.slice(2),t?2:8):Xp.test(r)?Fa:+r}function vh(r){return xn(r)?ch(r):uh(r)}function Sh(r){return r?ih(r,vh(r)):[]}qa.exports=dh});var Ha=h((Vw,Ga)=>{var xh="[object Boolean]",_h=Object.prototype,Oh=_h.toString;function Ch(r){return r===!0||r===!1||Ah(r)&&Oh.call(r)==xh}function Ah(r){return!!r&&typeof r=="object"}Ga.exports=Ch});var za=h((Gw,Xa)=>{var Wa=1/0,Th=17976931348623157e292,Ba=NaN,kh="[object Symbol]",Ph=/^\s+|\s+$/g,Lh=/^[-+]0x[0-9a-f]+$/i,Ih=/^0b[01]+$/i,Nh=/^0o[0-7]+$/i,Mh=parseInt,Dh=Object.prototype,Fh=Dh.toString;function Uh(r){return typeof r=="number"&&r==Gh(r)}function Ya(r){var e=typeof r;return!!r&&(e=="object"||e=="function")}function jh(r){return!!r&&typeof r=="object"}function qh(r){return typeof r=="symbol"||jh(r)&&Fh.call(r)==kh}function Vh(r){if(!r)return r===0?r:0;if(r=Hh(r),r===Wa||r===-Wa){var e=r<0?-1:1;return e*Th}return r===r?r:0}function Gh(r){var e=Vh(r),t=e%1;return e===e?t?e-t:e:0}function Hh(r){if(typeof r=="number")return r;if(qh(r))return Ba;if(Ya(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=Ya(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=r.replace(Ph,"");var t=Ih.test(r);return t||Nh.test(r)?Mh(r.slice(2),t?2:8):Lh.test(r)?Ba:+r}Xa.exports=Uh});var Ka=h((Hw,Ja)=>{var Wh="[object Number]",Bh=Object.prototype,Yh=Bh.toString;function Xh(r){return!!r&&typeof r=="object"}function zh(r){return typeof r=="number"||Xh(r)&&Yh.call(r)==Wh}Ja.exports=zh});var tl=h((Ww,el)=>{var Jh="[object Object]";function Kh(r){var e=!1;if(r!=null&&typeof r.toString!="function")try{e=!!(r+"")}catch{}return e}function Qh(r,e){return function(t){return r(e(t))}}var Zh=Function.prototype,Qa=Object.prototype,Za=Zh.toString,eg=Qa.hasOwnProperty,tg=Za.call(Object),rg=Qa.toString,ng=Qh(Object.getPrototypeOf,Object);function ig(r){return!!r&&typeof r=="object"}function sg(r){if(!ig(r)||rg.call(r)!=Jh||Kh(r))return!1;var e=ng(r);if(e===null)return!0;var t=eg.call(e,"constructor")&&e.constructor;return typeof t=="function"&&t instanceof t&&Za.call(t)==tg}el.exports=sg});var nl=h((Bw,rl)=>{var og="[object String]",ag=Object.prototype,lg=ag.toString,cg=Array.isArray;function ug(r){return!!r&&typeof r=="object"}function fg(r){return typeof r=="string"||!cg(r)&&ug(r)&&lg.call(r)==og}rl.exports=fg});var ll=h((Yw,al)=>{var mg="Expected a function",il=1/0,dg=17976931348623157e292,sl=NaN,pg="[object Symbol]",hg=/^\s+|\s+$/g,gg=/^[-+]0x[0-9a-f]+$/i,yg=/^0b[01]+$/i,Eg=/^0o[0-7]+$/i,wg=parseInt,bg=Object.prototype,Rg=bg.toString;function $g(r,e){var t;if(typeof e!="function")throw new TypeError(mg);return r=Og(r),function(){return--r>0&&(t=e.apply(this,arguments)),r<=1&&(e=void 0),t}}function vg(r){return $g(2,r)}function ol(r){var e=typeof r;return!!r&&(e=="object"||e=="function")}function Sg(r){return!!r&&typeof r=="object"}function xg(r){return typeof r=="symbol"||Sg(r)&&Rg.call(r)==pg}function _g(r){if(!r)return r===0?r:0;if(r=Cg(r),r===il||r===-il){var e=r<0?-1:1;return e*dg}return r===r?r:0}function Og(r){var e=_g(r),t=e%1;return e===e?t?e-t:e:0}function Cg(r){if(typeof r=="number")return r;if(xg(r))return sl;if(ol(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=ol(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=r.replace(hg,"");var t=yg.test(r);return t||Eg.test(r)?wg(r.slice(2),t?2:8):gg.test(r)?sl:+r}al.exports=vg});var yl=h((Xw,gl)=>{var cl=Qr(),Ag=bn(),Tg=wn(),ul=Ot(),kg=Va(),Yt=Ha(),fl=za(),On=Ka(),dl=tl(),ge=nl(),Pg=ll(),{KeyObject:Lg,createSecretKey:Ig,createPrivateKey:Ng}=require("crypto"),pl=["RS256","RS384","RS512","ES256","ES384","ES512","HS256","HS384","HS512","none"];Ag&&pl.splice(3,0,"PS256","PS384","PS512");var Mg={expiresIn:{isValid:function(r){return fl(r)||ge(r)&&r},message:'"expiresIn" should be a number of seconds or string representing a timespan'},notBefore:{isValid:function(r){return fl(r)||ge(r)&&r},message:'"notBefore" should be a number of seconds or string representing a timespan'},audience:{isValid:function(r){return ge(r)||Array.isArray(r)},message:'"audience" must be a string or array'},algorithm:{isValid:kg.bind(null,pl),message:'"algorithm" must be a valid string enum value'},header:{isValid:dl,message:'"header" must be an object'},encoding:{isValid:ge,message:'"encoding" must be a string'},issuer:{isValid:ge,message:'"issuer" must be a string'},subject:{isValid:ge,message:'"subject" must be a string'},jwtid:{isValid:ge,message:'"jwtid" must be a string'},noTimestamp:{isValid:Yt,message:'"noTimestamp" must be a boolean'},keyid:{isValid:ge,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'}},Dg={iat:{isValid:On,message:'"iat" should be a number of seconds'},exp:{isValid:On,message:'"exp" should be a number of seconds'},nbf:{isValid:On,message:'"nbf" should be a number of seconds'}};function hl(r,e,t,n){if(!dl(t))throw new Error('Expected "'+n+'" to be a plain object.');Object.keys(t).forEach(function(i){let s=r[i];if(!s){if(!e)throw new Error('"'+i+'" is not allowed in "'+n+'"');return}if(!s.isValid(t[i]))throw new Error(s.message)})}function Fg(r){return hl(Mg,!1,r,"options")}function Ug(r){return hl(Dg,!0,r,"payload")}var ml={audience:"aud",issuer:"iss",subject:"sub",jwtid:"jti"},jg=["expiresIn","notBefore","noTimestamp","audience","issuer","subject","jwtid"];gl.exports=function(r,e,t,n){typeof t=="function"?(n=t,t={}):t=t||{};let i=typeof r=="object"&&!Buffer.isBuffer(r),s=Object.assign({alg:t.algorithm||"HS256",typ:i?"JWT":void 0,kid:t.keyid},t.header);function o(u){if(n)return n(u);throw u}if(!e&&t.algorithm!=="none")return o(new Error("secretOrPrivateKey must have a value"));if(e!=null&&!(e instanceof Lg))try{e=Ng(e)}catch{try{e=Ig(typeof e=="string"?Buffer.from(e):e)}catch{return o(new Error("secretOrPrivateKey is not valid key material"))}}if(s.alg.startsWith("HS")&&e.type!=="secret")return o(new Error(`secretOrPrivateKey must be a symmetric key when using ${s.alg}`));if(/^(?:RS|PS|ES)/.test(s.alg)){if(e.type!=="private")return o(new Error(`secretOrPrivateKey must be an asymmetric key when using ${s.alg}`));if(!t.allowInsecureKeySizes&&!s.alg.startsWith("ES")&&e.asymmetricKeyDetails!==void 0&&e.asymmetricKeyDetails.modulusLength<2048)return o(new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${s.alg}`))}if(typeof r>"u")return o(new Error("payload is required"));if(i){try{Ug(r)}catch(u){return o(u)}t.mutatePayload||(r=Object.assign({},r))}else{let u=jg.filter(function(c){return typeof t[c]<"u"});if(u.length>0)return o(new Error("invalid "+u.join(",")+" option for "+typeof r+" payload"))}if(typeof r.exp<"u"&&typeof t.expiresIn<"u")return o(new Error('Bad "options.expiresIn" option the payload already has an "exp" property.'));if(typeof r.nbf<"u"&&typeof t.notBefore<"u")return o(new Error('Bad "options.notBefore" option the payload already has an "nbf" property.'));try{Fg(t)}catch(u){return o(u)}if(!t.allowInvalidAsymmetricKeyTypes)try{Tg(s.alg,e)}catch(u){return o(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=cl(t.notBefore,a)}catch(u){return o(u)}if(typeof r.nbf>"u")return o(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=cl(t.expiresIn,a)}catch(u){return o(u)}if(typeof r.exp>"u")return o(new Error('"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'))}Object.keys(ml).forEach(function(u){let c=ml[u];if(typeof t[u]<"u"){if(typeof r[c]<"u")return o(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&&Pg(n),ul.createSign({header:s,privateKey:e,payload:r,encoding:l}).once("error",n).once("done",function(u){if(!t.allowInsecureKeySizes&&/^(?:RS|PS)/.test(s.alg)&&u.length<256)return n(new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${s.alg}`));n(null,u)});else{let u=ul.sign({header:s,payload:r,secret:e,encoding:l});if(!t.allowInsecureKeySizes&&/^(?:RS|PS)/.test(s.alg)&&u.length<256)throw new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${s.alg}`);return u}}});var wl=h((zw,El)=>{El.exports={decode:zr(),verify:Ma(),sign:yl(),JsonWebTokenError:He(),NotBeforeError:Jr(),TokenExpiredError:Kr()}});(function(){Yn().config(Object.assign({},zn(),Kn()(process.argv)))})();var Ql=require("fs"),Zl=require("path");var Jl=N(lt());var re=N(require("fs")),vr=N(require("path")),di=N(require("os"));var Dc=process.stdout.isTTY===!0&&!process.env.NO_COLOR,me=r=>Dc?r:"",_=me("\x1B[32m"),P=me("\x1B[33m"),T=me("\x1B[36m"),de=me("\x1B[35m"),y=me("\x1B[31m"),E=me("\x1B[2m"),K=me("\x1B[1m"),m=me("\x1B[0m");var ci="app.boxel.realms";var Fc={"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"},Ly=Object.keys(Fc);function C(r){return r.endsWith("/")?r:`${r}/`}async function ui(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 Uc(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 Er(r,e){let t=await Uc(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 o=await i.text();throw new Error(`Realm server session failed: ${i.status} ${o}`)}let s=i.headers.get("Authorization");if(!s)throw new Error("Realm server session response did not include an Authorization header");return s}async function wr(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 br(r){return new URL(`_matrix/client/v3/user/${encodeURIComponent(r.userId)}/account_data/${ci}`,r.matrixUrl).href}async function ct(r){try{let e=await fetch(br(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 fi(r,e){let t=await ct(r);if(!t.includes(e)){t.push(e);let n=await fetch(br(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 mi(r,e){let t=C(e),n=await ct(r),i=n.filter(o=>C(o)!==t);if(i.length===n.length)return!1;let s=await fetch(br(r),{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r.accessToken}`},body:JSON.stringify({realms:i})});if(!s.ok){let o=await s.text();throw new Error(`Failed to update Matrix account data: ${s.status} ${o}`)}return!0}var jc=vr.join(di.homedir(),".boxel-cli"),qc="profiles.json",L="No active profile. Run `boxel profile add` to create one.";function ut(r){return r.endsWith(":stack.cards")?"staging":r.endsWith(":boxel.ai")?"production":r.endsWith(":localhost")?"local":"unknown"}function _e(r){let e=r.match(/^@([^:]+):/);return e?e[1]:r}function ft(r){let e=r.match(/:([^:]+)$/);return e?e[1]:"unknown"}function ie(r){let e=_e(r),t=ft(r);return`${E}[${m}${T}${e}${m} ${E}\xB7${m} ${de}${t}${m}${E}]${m}`}var $r=class{config;configDir;profilesFile;constructor(e){this.configDir=e||jc,this.profilesFile=vr.join(this.configDir,qc),this.config=this.loadConfig()}ensureConfigDir(){re.existsSync(this.configDir)||re.mkdirSync(this.configDir,{recursive:!0})}loadConfig(){let e={profiles:{},activeProfile:null};if(re.existsSync(this.profilesFile))try{let t=re.readFileSync(this.profilesFile,"utf-8"),n=JSON.parse(t);if(n&&typeof n=="object"&&!Array.isArray(n)){let i=n,s=i.profiles&&typeof i.profiles=="object"&&!Array.isArray(i.profiles)?i.profiles:null,o=i.activeProfile===null||typeof i.activeProfile=="string"?i.activeProfile:null;if(s)return{profiles:s,activeProfile:o}}}catch{}return e}saveConfig(){this.ensureConfigDir(),re.writeFileSync(this.profilesFile,JSON.stringify(this.config,null,2),{mode:384});try{re.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,s){let o=ut(e),a=_e(e);if(o==="unknown"&&(!i||!s))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=o==="production"?"https://matrix.boxel.ai":"https://matrix-staging.stack.cards",u=o==="production"?"https://app.boxel.ai/":"https://realms-staging.stack.cards/",c=ft(e),f={displayName:n||`${a} \xB7 ${c}`,matrixUrl:i||l,realmServerUrl:s||u,password:t};this.config.profiles[e]=f,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:_e(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,s=process.env.REALM_SERVER_URL;return t&&n&&i&&s?{matrixUrl:t,username:n,password:i,realmServerUrl:s,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=_e(t);return ui(n.matrixUrl,i,n.password)}async getOrRefreshServerToken(){let e=this.getRealmServerToken();if(e)return e;let t=await this.loginToMatrix(),i=this.getActiveProfile().profile.realmServerUrl.replace(/\/$/,""),s=await Er(t,i);return this.setRealmServerToken(s),s}async refreshServerToken(){let e=await this.loginToMatrix(),n=this.getActiveProfile().profile.realmServerUrl.replace(/\/$/,""),i=await Er(e,n);return this.setRealmServerToken(i),i}findRealmTokenForUrl(e){let n=this.getActiveProfile()?.profile.realmTokens;if(n){for(let[i,s]of Object.entries(n))if(e.startsWith(i)&&s)return s}}async fetchAndStoreAllRealmTokens(){let e=await this.getOrRefreshServerToken(),n=this.getActiveProfile().profile.realmServerUrl.replace(/\/$/,""),i=await wr(n,e);for(let[s,o]of Object.entries(i))this.setRealmToken(s,o)}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,s=new Headers(t?.headers);for(let[o,a]of s)i.set(o,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 s=this.getActiveProfile();if(s&&(s.profile.realmTokens={},s.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 o=this.buildHeaders(e,t,i);return await fetch(e,{...t,headers:o})}async authedRealmServerFetch(e,t){let n=await this.getOrRefreshServerToken(),i=this.buildHeaders(e,t,n),s=await fetch(e,{...t,headers:i});return s.status===401&&(n=await this.refreshServerToken(),i=this.buildHeaders(e,t,n),s=await fetch(e,{...t,headers:i})),s}async fetchAndStoreRealmToken(e,t){let i=this.getActiveProfile().profile.realmServerUrl.replace(/\/$/,""),o=(await wr(i,t))[e];return o&&this.setRealmToken(e,o),o}async addToUserRealms(e){let t=await this.loginToMatrix();await fi(t,e)}async removeFromUserRealms(e){let t=await this.loginToMatrix();return mi(t,e)}async getUserRealms(){let e=await this.loginToMatrix();return ct(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 o=e.includes("boxel.ai")?"boxel.ai":"stack.cards",a=`@${t}:${o}`;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:${m} ${ie(e.id)}`),console.log(` ${E}Display Name:${m} ${e.profile.displayName}`),console.log(` ${E}Matrix URL:${m} ${e.profile.matrixUrl}`),console.log(` ${E}Realm Server:${m} ${e.profile.realmServerUrl}`)):process.env.MATRIX_USERNAME?(console.log(`
33
- ${K}Using environment variables${m} (no profile active)`),console.log(` ${E}Username:${m} ${process.env.MATRIX_USERNAME}`)):(console.log(`
34
- ${P}No active profile and no environment variables set.${m}`),console.log(`Run ${T}boxel profile add${m} to create a profile.`))}},Rr=null;function O(){return Rr||(Rr=new $r),Rr}var Sr=N(require("readline")),pi=require("stream");function J(r){let e=Sr.createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{e.question(r,n=>{e.close(),t(n.trim())})})}function xr(r){let e=new pi.Writable({write:(n,i,s)=>s()}),t=Sr.createInterface({input:process.stdin,output:e,terminal:!0});return new Promise((n,i)=>{let s=process.stdin,o=s.readableFlowing;s.isTTY&&s.setRawMode(!0);let a=()=>{s.removeListener("data",l),s.isTTY&&s.setRawMode(!1),t.close(),o||s.pause()},l=c=>{try{let f=c.toString().split("\x1B[200~").join("").split("\x1B[201~").join("");for(let d of f)if(d===`
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===`
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(f){a(),i(f)}},u="";try{process.stdout.write(r),s.on("data",l),s.resume()}catch(c){a(),i(c)}})}async function pe(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 xr("Realm secret seed: ")}}var _r={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 mt(r,e){let t=r.trim(),n;try{n=new URL(t)}catch{console.error(`${y}Error:${m} ${e} "${r}" is not a valid URL.`),process.exit(1)}return n.protocol!=="http:"&&n.protocol!=="https:"&&(console.error(`${y}Error:${m} ${e} "${r}" must use http:// or https://.`),process.exit(1)),t}function Vc(r){return r.toLowerCase().replace(/\//g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function hi(){let r=process.env.BOXEL_ENVIRONMENT;if(!r||!r.trim())return null;let e=Vc(r);return e||(console.error(`${y}Error:${m} 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 yi(r,e,t){let n=O();switch(r){case"list":await gi(n);break;case"add":{let i=t?.password||process.env.BOXEL_PASSWORD;if(t?.user&&i){let s=t.matrixUrl?mt(t.matrixUrl,"--matrix-url"):void 0,o=t.realmServerUrl?mt(t.realmServerUrl,"--realm-server-url"):void 0,c=!(ut(t.user)!=="unknown")&&(!s||!o)?hi():null;c&&console.log(`${E}Using BOXEL_ENVIRONMENT=${process.env.BOXEL_ENVIRONMENT}${m}`),await Yc(n,t.user,i,t.name,s??c?.matrixUrl,o??c?.realmServerUrl)}else await Hc(n,hi());break}case"switch":e||(console.error(`${y}Error:${m} Please specify a profile to switch to.`),console.log("Usage: boxel profile switch <profile-id>"),console.log(`
37
- Available profiles:`),await gi(n),process.exit(1)),await Wc(n,e);break;case"remove":e||(console.error(`${y}Error:${m} Please specify a profile to remove.`),process.exit(1)),await Bc(n,e);break;case"migrate":await Xc(n);break;default:n.printStatus(),console.log(`
38
- ${E}Commands:${m}`),console.log(` ${T}boxel profile list${m} List all profiles`),console.log(` ${T}boxel profile add${m} Add a new profile`),console.log(` ${T}boxel profile switch${m} Switch active profile`),console.log(` ${T}boxel profile remove${m} Remove a profile`),console.log(` ${T}boxel profile migrate${m} Import from .env file`)}}async function gi(r){let e=r.listProfiles(),t=r.getActiveProfileId();if(e.length===0){console.log(`
39
- ${P}No profiles configured.${m}`),console.log(`Run ${T}boxel profile add${m} to create one.`);return}console.log(`
40
- ${K}Saved Profiles:${m}
41
- `);for(let n of e){let i=r.getProfile(n),s=n===t,o=ut(n),a=s?`${_}\u2605${m} `:" ",l=ft(n),u=o==="production"?de:T;console.log(`${a}${K}${n}${m}`),console.log(` ${E}Name:${m} ${i.displayName}`),console.log(` ${E}Environment:${m} ${u}${l}${m}`),console.log(` ${E}Realm Server:${m} ${i.realmServerUrl}`),console.log("")}t&&console.log(`${E}\u2605 = active profile${m}`)}async function Gc(){console.log("Which environment?"),console.log(` ${T}1${m}) Staging (realms-staging.stack.cards)`),console.log(` ${de}2${m}) Production (app.boxel.ai)`),console.log(` ${_}3${m}) Local (localhost:4201)`),console.log(` ${P}4${m}) Custom (enter your own URLs)`);let r=await J(`
42
- Choice [1/2/3/4]: `);if(r==="4"){let e=await J("Matrix server URL: ");e||(console.error(`${y}Error:${m} Matrix server URL is required.`),process.exit(1));let t=mt(e,"Matrix server URL"),n=await J("Realm server URL: ");n||(console.error(`${y}Error:${m} Realm server URL is required.`),process.exit(1));let i=mt(n,"Realm server URL"),s=new URL(t).hostname||"custom";return{domain:await J(`Domain for Matrix ID [${s}]: `)||s,matrixUrl:t,realmServerUrl:i}}return r==="3"?{..._r.local}:r==="2"?{..._r.production}:{..._r.staging}}async function Hc(r,e){console.log(`
43
- ${K}Add New Profile${m}
44
- `);let t,n,i;if(e)console.log(`${E}Using BOXEL_ENVIRONMENT=${process.env.BOXEL_ENVIRONMENT}${m}`),t=e.domain,n=e.matrixUrl,i=e.realmServerUrl;else{let f=await Gc();t=f.domain,n=f.matrixUrl,i=f.realmServerUrl}console.log(`
45
- Enter your Boxel username (without @ or domain)`),console.log(`${E}Example: ctse, aallen90${m}`);let s=await J("Username: ");s||(console.error(`${y}Error:${m} Username is required.`),process.exit(1));let o=`@${s}:${t}`;if(r.getProfile(o)&&(console.log(`
46
- ${P}Profile ${o} already exists.${m}`),(await J("Overwrite? [y/N]: ")).toLowerCase()!=="y")){console.log("Cancelled.");return}let a=await xr("Password: ");a||(console.error(`${y}Error:${m} Password is required.`),process.exit(1));let l=`${s} \xB7 ${t}`,c=await J(`Display name [${l}]: `)||l;await r.addProfile(o,a,c,n,i),console.log(`
47
- ${_}\u2713${m} Profile created: ${ie(o)}`),r.getActiveProfileId()===o?console.log(`${E}This profile is now active.${m}`):(await J("Switch to this profile now? [Y/n]: ")).toLowerCase()!=="n"&&(r.switchProfile(o),console.log(`${_}\u2713${m} Switched to ${ie(o)}`))}async function Wc(r,e){let t=r.listProfiles(),n=e;if(!t.includes(e)){let i=t.filter(s=>{let o=_e(s);return s.includes(e)||o===e});if(i.length===0){console.error(`${y}Error:${m} Profile not found: ${e}`),console.log(`
48
- Available profiles:`);for(let s of t)console.log(` ${s}`);process.exit(1)}else if(i.length===1)n=i[0];else{console.error(`${y}Error:${m} Ambiguous profile: ${e}`),console.log(`
49
- Matching profiles:`);for(let s of i)console.log(` ${s}`);process.exit(1)}}r.switchProfile(n)?console.log(`${_}\u2713${m} Switched to ${ie(n)}`):(console.error(`${y}Error:${m} Failed to switch profile.`),process.exit(1))}async function Bc(r,e){if(r.getProfile(e)||(console.error(`${y}Error:${m} Profile not found: ${e}`),process.exit(1)),(await J(`Remove profile ${e}? [y/N]: `)).toLowerCase()!=="y"){console.log("Cancelled.");return}if(await r.removeProfile(e)){console.log(`${_}\u2713${m} Profile removed.`);let i=r.getActiveProfileId();i&&console.log(`Active profile is now: ${ie(i)}`)}else console.error(`${y}Error:${m} Failed to remove profile.`),process.exit(1)}async function Yc(r,e,t,n,i,s){if((!e.startsWith("@")||!e.includes(":"))&&(console.error(`${y}Error:${m} Invalid Matrix ID format. Expected @user:domain`),process.exit(1)),r.getProfile(e)){console.log(`${P}Profile ${e} already exists. Updating password.${m}`),await r.updatePassword(e,t),n&&r.updateDisplayName(e,n),(i||s)&&r.updateUrls(e,{matrixUrl:i,realmServerUrl:s})&&console.log(`${E}Updated server URLs and cleared cached realm tokens.${m}`),console.log(`${_}\u2713${m} Profile updated: ${ie(e)}`);return}try{await r.addProfile(e,t,n,i,s)}catch(a){console.error(`${y}Error:${m} ${a instanceof Error?a.message:String(a)}`),process.exit(1)}console.log(`${_}\u2713${m} Profile created: ${ie(e)}`),r.getActiveProfileId()!==e&&console.log(`${E}Use 'boxel profile switch ${e}' to switch to this profile.${m}`)}async function Xc(r){console.log(`
50
- ${K}Migrate from .env${m}
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(`${P}No complete credentials found in environment variables.${m}`),console.log(`
52
- Required variables: MATRIX_URL, MATRIX_USERNAME, MATRIX_PASSWORD, REALM_SERVER_URL`);return}let s=await r.migrateFromEnv();s?s.created?(console.log(`${_}\u2713${m} Created profile: ${ie(s.profileId)}`),console.log(`
53
- ${E}You can now remove credentials from .env if desired.${m}`)):(console.log(`${P}Profile ${ie(s.profileId)} already exists.${m} Password has been updated if it changed.`),console.log(`
54
- ${E}Use 'boxel profile add -u ${s.profileId} -p <password>' to update other fields.${m}`)):console.log(`${P}Migration failed.${m}`)}var pt=!1,zc=console.log.bind(console),Jc=console.info.bind(console),Kc=console.debug.bind(console);function ht(r){if(r!==pt)if(pt=r,pt){let e=()=>{};console.log=e,console.info=e,console.debug=e}else console.log=zc,console.info=Jc,console.debug=Kc}var M={info(...r){pt||process.stderr.write(r.map(dt).join(" ")+`
55
- `)},warn(...r){process.stderr.write(r.map(dt).join(" ")+`
56
- `)},error(...r){process.stderr.write(r.map(dt).join(" ")+`
57
- `)},output(...r){process.stdout.write(r.map(dt).join(" ")+`
58
- `)}};function dt(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)}}async function Qc(r,e,t){let n=t?.profileManager??O();if(!n.getActiveProfile())throw new Error("No active profile. Run `boxel profile add` to create one.");let s=new URL(e,C(r)).href,o;try{o=await n.authedRealmFetch(s,{method:"GET",headers:{Accept:"*/*"}})}catch(l){return{ok:!1,error:l instanceof Error?l.message:String(l)}}if(!o.ok){let l=await o.text().catch(()=>"(no body)");return{ok:!1,status:o.status,error:`HTTP ${o.status}: ${l.slice(0,300)}`}}let a=await o.text();return{ok:!0,status:o.status,content:a}}function Ei(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 Qc(t.realm,e)}catch(i){console.error(`${y}Error:${m} ${i instanceof Error?i.message:String(i)}`),process.exit(1)}t.json?M.output(JSON.stringify(n,null,2)):n.ok?M.output(n.content??""):(console.error(`${E}Status:${m} ${n.status??"(no status)"}`),console.error(`${y}Error:${m} ${n.error}`)),n.ok||process.exit(1)})}async function Zc(r,e){let t=e?.profileManager??O();if(!t.getActiveProfile())return{ok:!1,error:L};let i=e?.cancelPending??!1,s=`${C(r)}_cancel-indexing-job`;try{let o=await t.authedRealmFetch(s,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({cancelPending:i})});if(!o.ok){let a=await o.text().catch(()=>"(no body)");return{ok:!1,error:`HTTP ${o.status}: ${a.slice(0,300)}`}}return{ok:!0}}catch(o){return{ok:!1,error:o instanceof Error?o.message:String(o)}}}function wi(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 Zc(e.realm,{cancelPending:e.cancelPending});if(e.json)M.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(`${_}Cancelled ${n} indexing jobs for ${e.realm}${m}`)}else console.error(`${y}Error:${m} ${t.error}`),process.exit(1)})}var eu=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"}),bi=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 Or(r){if(!r)return;let e=r.toLowerCase().replace(/[^a-z0-9]/g,"").replace(/^[0-9]+/,"");return eu[e.charAt(0)]}function Ri(){let r=Math.floor(Math.random()*bi.length);return bi[r]}var tu=/^[a-z0-9-]+$/;function vi(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 iu(e,t,n)})}async function ru(r,e,t={}){let n=t.profileManager??O(),i=n.getActiveProfile();if(!i)throw new Error("No active profile. Run `boxel profile add` to create one.");let s=i.profile.realmServerUrl.replace(/\/$/,""),o={endpoint:r,name:e,backgroundURL:t.background??Ri(),iconURL:t.icon??Or(e)??Or(r)},a=await n.authedRealmServerFetch(`${s}/_create-realm`,{method:"POST",headers:{"Content-Type":"application/vnd.api+json"},body:JSON.stringify({data:{type:"realm",attributes:o}})});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=su(d,s,r),g=await $i(n,p);try{await n.addToUserRealms(p)}catch{}return{realmUrl:p,created:!1,realmToken:g}}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=C(u),f=await $i(n,c);try{await n.addToUserRealms(c)}catch{}return t.waitForReady&&f&&await nu(c,f),{realmUrl:c,created:!0,realmToken:f}}async function $i(r,e){try{let t=await r.getOrRefreshServerToken();return await r.fetchAndStoreRealmToken(e,t)}catch{return}}async function nu(r,e){let t=new URL("_readiness-check",r).href,n=15e3,i=250,s=Date.now(),o;for(;Date.now()-s<n;){try{let a=await fetch(t,{headers:{Accept:"application/vnd.api+json",Authorization:e}});if(a.ok)return;o=`HTTP ${a.status}`}catch(a){o=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${o?`: ${o}`:""}`)}async function iu(r,e,t){tu.test(r)||(console.error("Error: realm name must contain only lowercase letters, numbers, and hyphens"),process.exit(1));try{let n=await ru(r,e,t),i=n.created?"created":"already exists";console.log(`${_}Realm ${i}:${m} ${T}${n.realmUrl}${m}`)}catch(n){console.error(`Error: ${n instanceof Error?n.message:String(n)}`),process.exit(1)}}function su(r,e,t){let n=r.match(/'(https?:\/\/[^']+)'/);if(n)return C(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 je=N(require("fs"));var Di=require("child_process"),G=N(require("fs/promises")),V=N(require("path"));var q=N(require("fs/promises")),j=N(require("path")),Dr=N(Pi());var Ir=class{value;next;constructor(e){this.value=e}},Fe=class{#e;#t;#r;constructor(){this.clear()}enqueue(e){let t=new Ir(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 Nr(r){let e=!1;if(typeof r=="object"&&({concurrency:r,rejectOnClear:e=!1}=r),Li(r),typeof e!="boolean")throw new TypeError("Expected `rejectOnClear` to be a boolean");let t=new Fe,n=0,i=()=>{n<r&&t.size>0&&(n++,t.dequeue().run())},s=()=>{n--,i()},o=async(u,c,f)=>{let d=(async()=>u(...f))();c(d);try{await d}catch{}s()},a=(u,c,f,d)=>{let p={reject:f};new Promise(g=>{p.run=g,t.enqueue(p)}).then(o.bind(void 0,u,c,d)),n<r&&i()},l=(u,...c)=>new Promise((f,d)=>{a(u,f,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){Li(u),r=u,queueMicrotask(()=>{for(;n<r&&t.size>0;)i()})}},map:{async value(u,c){let f=Array.from(u,(d,p)=>this(c,d,p));return Promise.all(f)}}}),l}function Li(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 vu=Dr.default.default||Dr.default,Su=new Set([".realm.json"]),Mr=1e4,xu=3e3;function F(r){let e=r.replace(/\\/g,"/").replace(/^\/+/,"");return Su.has(e)}async function Ii(r){try{return await q.access(r),!0}catch{return!1}}function Ni(r){try{return decodeURIComponent(r)}catch{return r}}var Ue={CardSource:"application/vnd.card+source",DirectoryListing:"application/vnd.api+json",Mtimes:"application/vnd.api+json"},_u=10,Mi=new Set(["node_modules"]),se=class{constructor(e,t){this.options=e;this.authenticator=t;this.normalizedRealmUrl=this.normalizeRealmUrl(e.realmUrl)}normalizedRealmUrl;ignoreCache=new Map;remoteLimit=Nr(_u);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.
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(`
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(`
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(`
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}
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
+ 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(`
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
+ 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(`
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.
59
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.
60
- 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.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 s=await i.json();if(s.data&&s.data.relationships){let o=Object.entries(s.data.relationships),a=await Promise.all(o.map(([l,u])=>{let f=u.meta.kind==="file",d=e?j.posix.join(e,l):l;return f?this.shouldIgnoreRemoteFile(d)?[]:[[d,!0]]:this.remoteLimit(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:Ue.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 s=Object.entries(i.data.attributes.mtimes);process.env.DEBUG&&(console.log(`Remote mtimes received: ${s.length} entries`),s.length>0&&console.log(`Sample: ${s[0][0]} = ${s[0][1]}`));for(let[o,a]of s){let l=o.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=j.join(this.options.localDir,e),i;try{i=await q.readdir(n,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")return t;throw o}let s=await Promise.all(i.map(async o=>{let a=j.join(n,o.name),l=e?j.posix.join(e,o.name):o.name;if(o.isDirectory()&&Mi.has(o.name))return[];if(await this.shouldIgnoreFile(l,a))return[];if(o.isFile()){let u=await q.stat(a);return[[l,{path:a,mtime:u.mtimeMs}]]}else if(o.isDirectory()){let u=await this.getLocalFileListWithMtimes(l);return Array.from(u.entries())}return[]}));for(let o of s)for(let[a,l]of o)t.set(a,l);return t}async getLocalFileList(e=""){let t=new Map,n=j.join(this.options.localDir,e),i;try{i=await q.readdir(n,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")return t;throw o}let s=await Promise.all(i.map(async o=>{let a=j.join(n,o.name),l=e?j.posix.join(e,o.name):o.name;if(o.isDirectory()&&Mi.has(o.name))return[];if(await this.shouldIgnoreFile(l,a))return[];if(o.isFile())return[[l,a]];if(o.isDirectory()){let u=await this.getLocalFileList(l);return Array.from(u.entries())}return[]}));for(let o of s)for(let[a,l]of o)t.set(a,l);return t}async uploadFile(e,t){if(F(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 q.readFile(t,"utf8"),i=this.buildFileUrl(e),s=await this.authenticator.authedRealmFetch(i,{method:"POST",headers:{"Content-Type":"text/plain;charset=UTF-8",Accept:Ue.CardSource},body:n});if(!s.ok)throw new Error(`Failed to upload: ${s.status} ${s.statusText}`);console.log(` Uploaded: ${e}`)}async uploadFilesAtomic(e,t){let n=Array.from(e.entries()).filter(([u])=>!F(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 f=await q.readFile(c,"utf8");return{op:t.has(u)?"add":"update",href:this.buildFileUrl(u),data:{type:"source",attributes:{content:f},meta:{}}}})),s=this.options.waitForIndex?`${this.normalizedRealmUrl}_atomic?waitForIndex=true`:`${this.normalizedRealmUrl}_atomic`,o=await this.authenticator.authedRealmFetch(s,{method:"POST",headers:{"Content-Type":"application/vnd.api+json",Accept:"application/vnd.api+json"},body:JSON.stringify({"atomic:operations":i})});if(o.status===201){let u=await o.json(),c=new Map(n.map(([d])=>[this.buildFileUrl(d),d])),f=(u["atomic:results"]??[]).map(d=>d.data?.id).filter(d=>typeof d=="string").map(d=>Ni(d)).map(d=>c.get(d)??d);for(let d of f)console.log(` Uploaded: ${d}`);return{succeeded:f}}let a={};try{a=await o.json()}catch{}let l=(a.errors??[]).map(u=>{let f=(u.detail??"").match(/Resource (\S+) /),d=f?Ni(f[1]):"";return{path:new Map(n.map(([g])=>[this.buildFileUrl(g),g])).get(d)??d,status:u.status??o.status,title:u.title??"Error"}});return{succeeded:[],error:{status:o.status,perFile:l,message:`Atomic upload failed: ${o.status} ${o.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:Ue.CardSource}});if(!i.ok)throw new Error(`Failed to download: ${i.status} ${i.statusText}`);let s=await i.text(),o=j.dirname(t);await q.mkdir(o,{recursive:!0}),await q.writeFile(t,s,"utf8"),console.log(` Downloaded: ${e}`)}async deleteFile(e){if(F(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:Ue.CardSource},signal:AbortSignal.timeout(Mr)})}catch(o){let a=Date.now()-n;if(console.error(` Delete request failed after ${a}ms: ${e}`),o instanceof Error&&(o.name==="TimeoutError"||o.name==="AbortError")){if(await this.verifyDeleteApplied(e)===!0){console.warn(` Delete response timed out after ${Mr}ms, but ${e} is already gone on the realm; continuing`);return}throw new Error(`Timed out deleting ${e} after ${Mr}ms`,{cause:o})}throw o}let s=Date.now()-n;if(console.log(` Delete response for ${e}: ${i.status} ${i.statusText} (${s}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:Ue.CardSource},signal:AbortSignal.timeout(xu)});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 q.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=vu(),s=e,o=this.options.localDir;for(;s.startsWith(o);){let a=j.join(s,".gitignore");if(await Ii(a))try{let c=await q.readFile(a,"utf8");i.add(c)}catch(c){console.warn(`Warning: Could not read .gitignore file at ${a}:`,c)}let l=j.join(s,".boxelignore");if(await Ii(l))try{let c=await q.readFile(l,"utf8");i.add(c)}catch(c){console.warn(`Warning: Could not read .boxelignore file at ${l}:`,c)}let u=j.dirname(s);if(u===s)break;s=u}return i})();return this.ignoreCache.set(e,n),n}async shouldIgnoreFile(e,t){let n=j.basename(e);if(n===".boxel-sync.json"||n.startsWith("."))return!0;let i=j.dirname(t),s=await this.getIgnoreInstance(i),o=e.replace(/\\/g,"/");return s.ignores(o)}shouldIgnoreRemoteFile(e){return!!j.basename(e).startsWith(".")}};async function Fr(r){try{return await G.access(r),!0}catch{return!1}}var B=class{workspaceDir;gitDir;constructor(e){this.workspaceDir=V.resolve(e),this.gitDir=V.join(this.workspaceDir,".boxel-history")}async init(){await Fr(this.gitDir)||await G.mkdir(this.gitDir,{recursive:!0});let e=V.join(this.gitDir,".git");await Fr(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 Fr(V.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 s=V.join(this.gitDir,i);try{await G.unlink(s)}catch(o){if(o.code!=="ENOENT")throw o}}})),await Promise.all(e.map(async i=>{let s=V.join(this.workspaceDir,i),o=V.join(this.gitDir,i),a=V.dirname(o);await G.mkdir(a,{recursive:!0}),await G.copyFile(s,o)}))}async getWorkspaceFiles(){let e=[],t=async(n,i="")=>{let s;try{s=await G.readdir(n,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")return;throw o}await Promise.all(s.map(async o=>{if(o.name===".boxel-history"||o.name===".boxel-sync.json"||o.name==="node_modules"||o.name.startsWith("."))return;let a=i?`${i}/${o.name}`:o.name;o.isDirectory()?await t(V.join(n,o.name),a):e.push(a)}))};return await t(this.workspaceDir),e}async getHistoryFiles(){let e=[],t=async(n,i="")=>{let s;try{s=await G.readdir(n,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")return;throw o}await Promise.all(s.map(async o=>{if(o.name===".git")return;let a=i?`${i}/${o.name}`:o.name;o.isDirectory()?await t(V.join(n,o.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(`
61
- `)){if(!n)continue;let i=n.substring(0,2),s=n.substring(3);if(i.includes("R")){let o=s.indexOf(" -> ");if(o!==-1){let a=s.substring(0,o),l=s.substring(o+4);t.push({file:a,status:"deleted"}),t.push({file:l,status:"added"});continue}}i.includes("D")?t.push({file:s,status:"deleted"}):i.includes("A")||i.includes("C")||i==="??"?t.push({file:s,status:"added"}):(i.includes("M")||i.includes("U")||i.includes("T"))&&t.push({file:s,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 s=this.classifyChanges(t),{message:o,description:a}=n?{message:n,description:""}:this.generateCommitMessage(e,t,s),l=s?"[MAJOR]":"[minor]",u=`[${e}]`,c=`${l} ${u} ${o}${a?`
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(`
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?`
62
68
 
63
- `+a:""}`;await this.git("commit","-m",c);let f=(await this.git("rev-parse","HEAD")).trim(),d=f.substring(0,7);return{hash:f,shortHash:d,message:o,description:a,date:new Date,isMajor:s,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 f=t[0],d=f.status==="added"?"Add":f.status==="deleted"?"Delete":"Update";return{message:`${i}: ${d} ${f.file}`,description:""}}let s=t.filter(f=>f.status==="added"),o=t.filter(f=>f.status==="modified"),a=t.filter(f=>f.status==="deleted"),l=[];s.length>0&&l.push(`+${s.length}`),o.length>0&&l.push(`~${o.length}`),a.length>0&&l.push(`-${a.length}`);let u=`${i}: ${t.length} files (${l.join(", ")})`,c=[];return s.length>0&&(c.push("Added:"),s.forEach(f=>c.push(` + ${f.file}`))),o.length>0&&(c.push("Modified:"),o.forEach(f=>c.push(` ~ ${f.file}`))),a.length>0&&(c.push("Deleted:"),a.forEach(f=>c.push(` - ${f.file}`))),{message:u,description:c.join(`
64
- `)}}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(),s=n.trim().split(`
65
- `).filter(o=>!(o.split("|")[2]??"").startsWith("[init]"));return Promise.all(s.map(async o=>{let[a,l,u,c]=o.split("|"),f=u.includes("[MAJOR]"),d=u.includes("[local]")?"local":u.includes("[remote]")?"remote":"manual",p=u.replace(/\[(MAJOR|minor)\]\s*/i,"").replace(/\[(local|remote|manual)\]\s*/i,""),g=await this.getCommitStats(a),S=i.get(a),z=!!S;return{hash:a,shortHash:l,message:p,description:"",date:new Date(c),isMajor:f,source:d,isMilestone:z,milestoneName:S,...g}}))}async getCommitStats(e){try{let n=(await this.git("show","--stat","--format=",e)).trim().split(`
66
- `),i=n[n.length-1]||"",s=i.match(/(\d+) files? changed/),o=i.match(/(\d+) insertions?/),a=i.match(/(\d+) deletions?/);return{filesChanged:s?parseInt(s[1]):0,insertions:o?parseInt(o[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(`
67
- `).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 o=>{let a=V.join(this.gitDir,o);try{await G.unlink(a)}catch(l){if(l.code!=="ENOENT")throw l}})),await this.git("checkout",e,"--",".");let n=await this.getHistoryFiles(),i=new Set(n),s=await this.getWorkspaceFiles();await Promise.all(s.map(async o=>{if(!F(o)&&!i.has(o)){let a=V.join(this.workspaceDir,o);try{await G.unlink(a)}catch(l){if(l.code!=="ENOENT")throw l}}})),await Promise.all(n.map(async o=>{if(F(o))return;let a=V.join(this.gitDir,o),l=V.join(this.workspaceDir,o),u=V.dirname(l);await G.mkdir(u,{recursive:!0}),await G.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 s=await this.getCheckpoints(e+1);if(e<1||e>s.length)return null;n=s[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(`
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
+ `)}}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
+ `).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
+ `),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(`
68
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(`
69
- `).filter(Boolean))try{let i=(await this.git("rev-list","-1",n)).trim(),s=n.replace("milestone/","").replace(/-/g," ");e.set(i,s)}catch{}}catch{}return e}async getMilestones(){return(await this.getCheckpoints(100)).filter(t=>t.isMilestone)}git(...e){return new Promise((t,n)=>{let i=(0,Di.spawn)("git",e,{cwd:this.gitDir}),s="",o="";i.stdout.on("data",a=>{s+=a.toString("utf-8")}),i.stderr.on("data",a=>{o+=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: ${o}`));return}t(s)})})}};function Fi(r,e){let t=r.trim();if(t==="")return{kind:"none"};if(t.length===7){let i=e.filter(s=>s.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 Ui=100;function yt(r){return r instanceof Error?r.message:String(r)}async function Ou(r,e){if(!je.existsSync(r))return{ok:!1,error:`Directory not found: ${r}`};try{let t=new B(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: ${yt(t)}`}}}async function Cu(r,e){if(!je.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 B(r);await n.isInitialized()||await n.init();let i=await n.detectCurrentChanges(),s=await n.createCheckpoint("manual",i,t);return s?{ok:!0,created:s}:{ok:!1,error:"No changes to checkpoint."}}catch(n){return{ok:!1,error:`Failed to create checkpoint: ${yt(n)}`}}}async function Au(r,e,t){if(!je.existsSync(r))return{ok:!1,error:`Directory not found: ${r}`};try{let n=new B(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),s=Fi(e,i);if(s.kind==="none")return{ok:!1,error:`Checkpoint not found: ${e}. Use a number (1-${i.length}) or a commit hash.`};if(s.kind==="ambiguous"){let o=s.matches.slice(0,5).map(l=>l.shortHash).join(", "),a=s.matches.length>5?", \u2026":"";return{ok:!1,error:`Ambiguous reference: ${e} matches ${s.matches.length} checkpoints (${o}${a}). Use a longer prefix or full hash.`}}return{ok:!0,target:s.target}}catch(n){return{ok:!1,error:`Failed to read checkpoint history: ${yt(n)}`}}}async function Tu(r,e){if(!je.existsSync(r))return{ok:!1,error:`Directory not found: ${r}`};try{let t=new B(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: ${yt(t)}`}}}function ku(r){return r==="local"?`${_}LOCAL${m}`:r==="remote"?`${T}SERVER${m}`:`${de}MANUAL${m}`}function ji(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 Pu(r,e,t){if(r.length===0){console.log("No checkpoints found.");return}console.log(`
70
- ${K}Checkpoint History${m}
71
- `);let n=String(r.length).length;r.forEach((i,s)=>{let o=s+1,a=`${E}${String(o).padStart(n," ")}${m}`,l=i.isMajor?`${P}[MAJOR]${m}`:`${E}[minor]${m}`,u=i.isMilestone?`${P}\u2B50${m} ${de}[${i.milestoneName}]${m} `:"";console.log(`${a} ${P}${i.shortHash}${m} ${u}${ku(i.source)} ${l} ${i.message} ${E}(${i.filesChanged} files)${m}`),console.log(` ${E}${ji(i.date)}${m}
72
- `)}),e&&console.log(`${E}Showing first ${t} checkpoints. Pass --limit <n> to see more.${m}`),console.log(`${E}Restore: boxel realm history <local-dir> -r <ref>${m}`)}function Lu(r){if(r===void 0)return Ui;if(!/^\d+$/.test(r))return null;let e=parseInt(r,10);return e>0?e:null}function be(r){console.error(`${y}Error:${m} ${r}`),process.exit(1)}function qi(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: ${Ui})`).action(async(e,t)=>{t.restore!==void 0&&t.message!==void 0&&be("Only one of --restore or --message may be specified.");let n=Lu(t.limit);if(n===null&&be("--limit must be a positive integer."),t.message!==void 0){let s=await Cu(e,t.message);s.ok||be(s.error),console.log(`${_}\u2713${m} Checkpoint created: ${P}${s.created.shortHash}${m} ${s.created.message}`);return}if(t.restore!==void 0){let s=await Au(e,t.restore,n);s.ok||be(s.error);let o=s.target;if(!t.yes){process.stdin.isTTY||be("--restore overwrites local files. Pass --yes to confirm in non-interactive mode."),console.log(`
73
- ${K}Restoring to:${m} ${P}${o.shortHash}${m} - ${o.message}`),console.log(`${E}${ji(o.date)}${m}
74
- `);let l=await J(`${P}This will overwrite current files. Continue? (y/N) ${m}`);if(!/^y/i.test(l)){console.log(`${E}Restore cancelled.${m}`);return}}let a=await Tu(e,o.hash);a.ok||be(a.error),console.log(`${_}\u2713${m} Restored to ${P}${o.shortHash}${m} ${o.message}`),console.log(`${E}Run 'boxel realm sync <local-dir> <realm-url> --prefer-local' to push the restored state to the realm.${m}`);return}let i=await Ou(e,n);i.ok||be(i.error),Pu(i.checkpoints,i.truncated,n)})}var Iu="--all-accessible and --hidden are mutually exclusive";async function Nu(r={}){if(r.allAccessible&&r.hidden)return{realms:[],error:Iu};let e=r.profileManager??O(),t=e.getActiveProfile();if(!t)return{realms:[],error:L};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 s=await i.json(),o=Object.keys(s).map(C),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(C)),u=o.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,f)=>c.url.localeCompare(f.url)),{realms:u}}function Vi(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 Nu({allAccessible:e.allAccessible,hidden:e.hidden})}catch(n){console.error(`${y}Error:${m} ${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(`${y}Error:${m} ${t.error}`),process.exit(1)),t.realms.length===0){console.log(`${E}No realms found.${m}`);return}console.log(`${K}${t.realms.length} realm(s):${m}`);for(let n of t.realms){let i=n.hidden?` ${E}(hidden)${m}`:"";console.log(` ${T}${n.url}${m}${i}`)}})}var bl=N(wl()),Rl="realm_server";function qg(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 Vg(r,e=Rl){return`@${e}:${qg(r)}`}function Gg(r){return new URL(r).origin+"/"}function Hg(r){try{return new URL(r).href.replace(/\/+$/,"")+"/"}catch{throw new Error(`Invalid realm URL: ${r}`)}}var Xt=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??Rl,this.#r=e.botUserId,this.#i=e.expiresIn??"7d"}buildClaims(e){let t=Hg(e);return{user:this.#r??Vg(t,this.#t),realm:t,sessionRoom:void 0,permissions:[],realmServerURL:Gg(t)}}mintTokenForRealm(e){let t=this.buildClaims(e),n=this.#n.get(t.realm);if(n)return n;let i=bl.default.sign(t,this.#e,{expiresIn:this.#i});return this.#n.set(t.realm,i),i}#s(e){for(let s of this.#n.keys())if(e.startsWith(s))return s;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.#s(n),s=this.mintTokenForRealm(i),o=this.#o(e,t,s);return fetch(e,{...t,headers:o})}#o(e,t,n){let i=e instanceof Request?new Headers(e.headers):new Headers,s=new Headers(t?.headers);for(let[o,a]of s)i.set(o,a);return i.has("Authorization")||i.set("Authorization",n),i}registerRealmUrl(e){this.mintTokenForRealm(e)}};function ye(r){if(r.realmSecretSeed)try{let t=new Xt({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??O();return e.getActiveProfile()?{ok:!0,authenticator:e,mode:"profile"}:{ok:!1,error:L}}var zt=N(require("fs/promises")),$l=N(require("path")),Cn=class extends se{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 zt.access(this.options.localDir)}catch{console.log(`[DRY RUN] Would create directory: ${this.options.localDir}`)}else await zt.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 s=new B(this.options.localDir);if(i.size>0&&!this.options.dryRun){let l=Array.from(i).map(c=>({file:c,status:"deleted"})),u=await s.createCheckpoint("remote",l,`Pre-delete checkpoint: ${i.size} files not on server`);u&&console.log(`
75
- Checkpoint created before deletion: ${u.shortHash}`)}let o=await Promise.all(Array.from(t.keys()).map(l=>this.remoteLimit(async()=>{try{let u=$l.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=o.filter(l=>l!==null);let a=[];if(i.size>0&&(console.log(`
76
- 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 s.createCheckpoint("remote",l);if(u){let c=u.isMajor?"[MAJOR]":"[minor]";console.log(`
77
- Checkpoint created: ${u.shortHash} ${c} ${u.message}`)}}console.log("Pull completed")}};function vl(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 pe(n.realmSecretSeed===!0),s=await Wg(e,t,{delete:n.delete,dryRun:n.dryRun,realmSecretSeed:i});s.error&&(console.error(`Error: ${s.error}`),process.exit(s.files.length>0?2:1)),console.log("Pull completed successfully")})}async function Wg(r,e,t){let n;if(t.authenticator)n=t.authenticator;else{let i=ye({realmUrl:r,realmSecretSeed:t.realmSecretSeed,profileManager:t.profileManager});if(!i.ok)return{files:[],error:i.error};n=i.authenticator}try{let i=new Cn({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 Se=N(require("fs/promises")),An=N(require("path")),Sl=N(require("crypto"));function Bg(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 Jt(r){try{return await Se.access(r),!0}catch{return!1}}async function fe(r){let e=await Se.readFile(r);return Sl.createHash("md5").update(e).digest("hex")}async function xe(r){let e=An.join(r,".boxel-sync.json"),t;try{t=await Se.readFile(e,"utf8")}catch(i){if(i.code==="ENOENT")return null;throw i}let n;try{n=JSON.parse(t)}catch{return null}return Bg(n)?n:(console.warn("Warning: .boxel-sync.json is malformed or has an unexpected shape; falling back to a full upload."),null)}async function Ne(r,e){let t=An.join(r,".boxel-sync.json");await Se.writeFile(t,JSON.stringify(e,null,2))}var Yg=new Set(["index.json","realm.json"]),Tn=class extends se{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 xe(this.options.localDir),s={realmUrl:this.normalizedRealmUrl,files:{},remoteMtimes:{}},o=new Map,a=new Set;if(!this.pushOptions.force&&i!==null&&i.realmUrl===this.normalizedRealmUrl){console.log("Checking for changed files...");let c=0,[f,d]=await Promise.all([this.getRemoteMtimes(),Promise.all(Array.from(n.entries()).map(async([p,g])=>{if(F(p))return{relativePath:p,localPath:g,currentHash:"",protected:!0};let S=await fe(g);return{relativePath:p,localPath:g,currentHash:S,protected:!1}}))]);for(let p of d){if(p.protected){c++;continue}let g=i.files[p.relativePath],S=i.remoteMtimes?.[p.relativePath],z=f.get(p.relativePath),rt=g!==p.currentHash,R=g!==void 0&&!t.has(p.relativePath),$=S!==void 0&&z!==void 0&&z!==S;rt||R||$?(o.set(p.relativePath,p.localPath),!rt&&(R||$)&&a.add(p.relativePath)):(c++,s.files[p.relativePath]=p.currentHash,S!==void 0&&(s.remoteMtimes[p.relativePath]=S))}if(c>0&&console.log(`Skipping ${c} unchanged files`),a.size>0){let p=Array.from(a),g=p.slice(0,5).join(", "),S=p.length>5?", ...":"";console.warn(`Warning: ${a.size} file(s) changed on the realm since your last push; your local versions will overwrite them: ${g}${S}`)}}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,f]of n)F(c)||o.set(c,f)}let u=!1;if(o.size===0)console.log("No files to upload - everything is up to date");else{console.log(`Uploading ${o.size} file(s) via /_atomic...`);let c=new Set,f=this.pushOptions.force||!i;for(let p of o.keys())if(f)t.has(p)||c.add(p);else{let g=i.files[p]!==void 0,S=g&&!t.has(p);(!g||S)&&c.add(p)}let d=await this.uploadFilesAtomic(o,c);if(d.error){u=!0,this.hasError=!0,console.error(d.error.message);for(let p of d.error.perFile){let g;p.status===409?g=`${p.path} was created on the realm concurrently \u2014 run with --force to overwrite.`:p.status===404?g=`${p.path} was removed from the realm concurrently \u2014 run with --force to re-create it from your local copy.`:g=`${p.path}: ${p.title}`,console.error(` ${g}`)}}else if(d.succeeded.length>0){let p=await Promise.all(d.succeeded.map(async g=>({rel:g,hash:await fe(o.get(g))})));for(let{rel:g,hash:S}of p)s.files[g]=S}}if(this.pushOptions.deleteRemote){let c=new Set(t.keys()),f=[];for(let d of c){if(F(d)){c.delete(d);continue}Yg.has(d)&&(c.delete(d),f.push(d))}for(let d of n.keys())c.delete(d);if(f.length>0&&console.log(`Skipping ${f.length} realm-managed remote artifact(s): ${f.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(g){this.hasError=!0,console.error(`Error deleting ${p}:`,g)}}}if(!this.options.dryRun&&!u&&o.size>0)try{let c=await this.getRemoteMtimes();for(let f of Object.keys(s.files)){let d=c.get(f);d!==void 0&&(s.remoteMtimes[f]=d)}}catch(c){console.warn("Could not refresh remote mtimes after upload:",c)}if(s.remoteMtimes&&Object.keys(s.remoteMtimes).length===0&&delete s.remoteMtimes,!this.options.dryRun&&!u&&await Ne(this.options.localDir,s),!this.options.dryRun&&o.size>0&&!u){let c=new B(this.options.localDir),f=Array.from(o.keys()).map(p=>({file:p,status:"modified"})),d=await c.createCheckpoint("local",f);if(d){let p=d.isMajor?"[MAJOR]":"[minor]";console.log(`
78
- Checkpoint created: ${d.shortHash} ${p} ${d.message}`)}}console.log("Push completed")}};function xl(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 pe(n.realmSecretSeed===!0);await Xg(e,t,{delete:n.delete,dryRun:n.dryRun,force:n.force,realmSecretSeed:i})})}async function Xg(r,e,t){let n;if(t.authenticator)n=t.authenticator;else{let i=ye({realmUrl:e,realmSecretSeed:t.realmSecretSeed,profileManager:t.profileManager});i.ok||(console.error(`Error: ${i.error}`),process.exit(1)),n=i.authenticator}await Jt(r)||(console.error(`Local directory does not exist: ${r}`),process.exit(1));try{let i=new Tn({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 _l(r){let e=C(r.realmUrl.trim()),t=r.profileManager??O(),n=t.getActiveProfile();if(!n)return{realmUrl:e,removed:!1,serverDeleted:!1,unlinked:!1,previousCount:0,nextCount:0,error:L};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 s=i.map(C),o=s.length,a=s.filter(d=>d===e).length;if(a===0)return{realmUrl:e,removed:!1,serverDeleted:!1,unlinked:!1,previousCount:o,nextCount:o,notInList:!0,error:"Realm is not in app.boxel.realms. Nothing to remove."};let l=o-a;if(r.dryRun)return{realmUrl:e,removed:!1,serverDeleted:!1,unlinked:!1,previousCount:o,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:o,nextCount:o,error:`Failed to reach realm server: ${d instanceof Error?d.message:String(d)}`}}if(!c.ok){let d=await zg(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:o,nextCount:o,error:p}}let f;try{f=await t.removeFromUserRealms(e)}catch(d){return{realmUrl:e,removed:!1,serverDeleted:!0,unlinked:!1,previousCount:o,nextCount:o,error:`Server delete succeeded, but Matrix unlink failed: ${d instanceof Error?d.message:String(d)}`}}return f?{realmUrl:e,removed:!0,serverDeleted:!0,unlinked:f,previousCount:o,nextCount:l}:{realmUrl:e,removed:!1,serverDeleted:!0,unlinked:!1,previousCount:o,nextCount:o,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 zg(r){try{return await r.text()}catch{return"<no response body>"}}function Ol(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=C(e.trim()),i=await _l({realmUrl:n,dryRun:!0});if(i.error&&!i.notInList&&(console.error(`${y}Error:${m} ${i.error}`),process.exit(1)),i.notInList&&(console.error(`${y}Error:${m} ${i.error}`),process.exit(1)),console.log(`Remove target: ${T}${i.realmUrl}${m}`),console.log(`${E}app.boxel.realms: ${i.previousCount} -> ${i.nextCount}${m}`),t.dryRun){console.log(`${E}[DRY RUN] No server delete or Matrix changes sent.${m}`);return}if(!t.yes){process.stdin.isTTY||(console.error(`${y}Error:${m} stdin is not a TTY. Pass --yes to confirm in non-interactive mode.`),process.exit(1));let o=await J("This will permanently delete the realm files, indexer state, and registry entry on the server. Proceed? (y/N) ");if(!/^y/i.test(o)){console.log(`${E}Cancelled.${m}`);return}}let s=await _l({realmUrl:n});(s.error||!s.removed)&&(console.error(`${y}Error:${m} ${s.error??"Removal did not complete."}`),s.serverDeleted&&!s.unlinked&&console.error(`${E}The realm is gone, but your account_data still references ${s.realmUrl}.${m}`),process.exit(1)),console.log(`${_}Removed:${m} ${T}${s.realmUrl}${m}`)})}var Pn=N(require("path"));function Cl(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 Al(r,e,t){let n=e.has(r),i=t?.remoteMtimes?.[r]!==void 0,s=t?.files[r]!==void 0,o=i||s;return n&&i?e.get(r)===t.remoteMtimes[r]?"unchanged":"changed":n&&s?"changed":n&&!o?"added":!n&&o?"deleted":"unchanged"}function Tl(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 kl(r,e,t,n){let{localStatus:i,remoteStatus:s,relativePath:o}=r;if(!n)return null;switch(n){case"prefer-local":return i==="deleted"?"push-delete":"push";case"prefer-remote":return s==="deleted"?"pull-delete":"pull";case"prefer-newest":{if(i==="deleted"&&s==="changed")return"pull";if(i==="changed"&&s==="deleted")return"push";let a=e.get(o),l=t.get(o);return a&&l!==void 0?a.mtime>l*1e3?"push":"pull":"push"}}}var Ln=class extends se{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(R){throw console.error("Failed to access realm:",R),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,s]=await Promise.all([this.getLocalFileListWithMtimes(),this.getRemoteMtimes(),xe(this.options.localDir)]),o=new Map;for(let[R,$]of n)o.set(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[R]of t)i.set(R,0)}console.log(`Found ${o.size} local files`),console.log(`Found ${i.size} remote files`),s&&s.realmUrl!==this.normalizedRealmUrl&&console.warn(`${P}Warning:${m} Manifest realm URL (${s.realmUrl}) differs from target (${this.normalizedRealmUrl}). Treating as first sync.`);let a=s&&s.realmUrl===this.normalizedRealmUrl?s:null,l=new Map;await Promise.all(Array.from(o.entries()).map(async([R,$])=>{F(R)||l.set(R,await fe($))}));let u=new Set;for(let R of o.keys())u.add(R);for(let R of i.keys())u.add(R);if(a){for(let R of Object.keys(a.files))u.add(R);if(a.remoteMtimes)for(let R of Object.keys(a.remoteMtimes))u.add(R)}let c=[];for(let R of u){if(F(R))continue;let $=Cl(R,l,a),x=Al(R,i,a),D=Tl($,x,this.syncOptions);c.push({relativePath:R,localStatus:$,remoteStatus:x,action:D})}let f=[],d=[],p=[],g=[],S=[],z=0;for(let R of c)switch(R.action){case"push":f.push(R.relativePath);break;case"pull":d.push(R.relativePath);break;case"push-delete":p.push(R.relativePath);break;case"pull-delete":g.push(R.relativePath);break;case"conflict":S.push(R);break;case"noop":z++;break}for(let R of S)switch(kl(R,n,i,this.conflictStrategy)){case"push":f.push(R.relativePath);break;case"pull":d.push(R.relativePath);break;case"push-delete":p.push(R.relativePath);break;case"pull-delete":g.push(R.relativePath);break;case"noop":break;default:this.skippedConflicts.push(R.relativePath);break}if(console.log(`
79
- ${E}Sync plan:${m}`),f.length>0&&console.log(` ${_}\u2191 Push:${m} ${f.length} file(s)`),d.length>0&&console.log(` ${T}\u2193 Pull:${m} ${d.length} file(s)`),p.length>0&&console.log(` ${y}\u2191 Delete remote:${m} ${p.length} file(s)`),g.length>0&&console.log(` ${y}\u2193 Delete local:${m} ${g.length} file(s)`),this.skippedConflicts.length>0){console.log(` ${P}\u26A0 Conflicts skipped:${m} ${this.skippedConflicts.length} file(s)`);for(let R of this.skippedConflicts)console.log(` ${R}`);console.log(` ${E}Use --prefer-local, --prefer-remote, or --prefer-newest to resolve.${m}`)}if(z>0&&console.log(` ${E}Unchanged: ${z} file(s)${m}`),f.length+d.length+p.length+g.length===0){console.log(`
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(`
82
+ No milestones marked yet.
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
+ `);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(`
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
+ 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(`
80
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(`
81
- Pulling ${d.length} file(s)...`);let R=await Promise.all(d.map($=>this.remoteLimit(async()=>{try{let x=Pn.join(this.options.localDir,$);return await this.downloadFile($,x),$}catch(x){return this.hasError=!0,console.error(`Error downloading ${$}:`,x),null}})));this.pulledFiles.push(...R.filter($=>$!==null))}if(f.length>0){console.log(`
82
- Pushing ${f.length} file(s)...`);let R=new Map;for(let D of f){let nt=o.get(D);nt&&R.set(D,nt)}let $=new Set;for(let D of R.keys()){let nt=a?.files[D]!==void 0,ec=i.has(D);!nt&&!ec&&$.add(D)}let x=await this.uploadFilesAtomic(R,$);if(x.error){this.hasError=!0,console.error(x.error.message);for(let D of x.error.perFile)console.error(` ${D.path}: ${D.title}`)}else this.pushedFiles.push(...x.succeeded)}if(p.length>0){console.log(`
83
- Deleting ${p.length} remote file(s)...`);let R=await Promise.all(p.map($=>this.remoteLimit(async()=>{try{return await this.deleteFile($),$}catch(x){return this.hasError=!0,console.error(`Error deleting remote ${$}:`,x),null}})));this.remoteDeletedFiles.push(...R.filter($=>$!==null))}if(g.length>0){console.log(`
84
- Deleting ${g.length} local file(s)...`);let R=await Promise.all(g.map(async $=>{try{let x=o.get($);return x?(await this.deleteLocalFile(x),$):null}catch(x){return this.hasError=!0,console.error(`Error deleting local ${$}:`,x),null}}));this.localDeletedFiles.push(...R.filter($=>$!==null))}if(!this.options.dryRun&&!this.hasError){let R=new Map;if(a)for(let[x,D]of Object.entries(a.files))R.set(x,D);for(let[x,D]of l)R.set(x,D);for(let x of this.pushedFiles){let D=o.get(x);D&&R.set(x,await fe(D))}for(let x of this.pulledFiles){let D=Pn.join(this.options.localDir,x);R.set(x,await fe(D))}for(let x of this.remoteDeletedFiles)R.delete(x);for(let x of this.localDeletedFiles)R.delete(x);let $=i;if(this.pushedFiles.length>0||this.remoteDeletedFiles.length>0)try{$=await this.getRemoteMtimes()}catch{console.warn("Could not refresh remote mtimes after sync")}await this.writeManifest(R,$)}if(!this.options.dryRun){let R=[...this.pushedFiles.map($=>({file:$,status:"modified"})),...this.pulledFiles.map($=>({file:$,status:"modified"})),...this.remoteDeletedFiles.map($=>({file:$,status:"deleted"})),...this.localDeletedFiles.map($=>({file:$,status:"deleted"}))];if(R.length>0){let x=await new B(this.options.localDir).createCheckpoint("local",R);if(x){let D=x.isMajor?"[MAJOR]":"[minor]";console.log(`
85
- Checkpoint created: ${x.shortHash} ${D} ${x.message}`)}}}console.log(`
86
- Sync completed`)}async writeManifest(t,n){let i={realmUrl:this.normalizedRealmUrl,files:{},remoteMtimes:{}};for(let[s,o]of t){i.files[s]=o;let a=n.get(s);a!==void 0&&a!==0&&(i.remoteMtimes[s]=a)}i.remoteMtimes&&Object.keys(i.remoteMtimes).length===0&&delete i.remoteMtimes,await Ne(this.options.localDir,i)}};function Pl(r){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(e,t,n)=>{let i=await pe(n.realmSecretSeed===!0),s=await Jg(e,t,{preferLocal:n.preferLocal,preferRemote:n.preferRemote,preferNewest:n.preferNewest,delete:n.delete,dryRun:n.dryRun,realmSecretSeed:i}),o=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(o?2:1)),console.log("Sync completed successfully")})}async function Jg(r,e,t){let n;if(t.authenticator)n=t.authenticator;else{let o=ye({realmUrl:e,realmSecretSeed:t.realmSecretSeed,profileManager:t.profileManager});if(!o.ok)return kn({error:o.error});n=o.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 Jt(r))return kn({error:`Local directory does not exist: ${r}`});let s;try{s=new Ln({realmUrl:e,localDir:r,preferLocal:t.preferLocal,preferRemote:t.preferRemote,preferNewest:t.preferNewest,deleteSync:t.delete,dryRun:t.dryRun,waitForIndex:t.waitForIndex},n),await s.sync()}catch(o){return{pushed:s?.pushedFiles.slice().sort()??[],pulled:s?.pulledFiles.slice().sort()??[],remoteDeleted:s?.remoteDeletedFiles.slice().sort()??[],localDeleted:s?.localDeletedFiles.slice().sort()??[],skippedConflicts:s?.skippedConflicts.slice().sort()??[],hasError:!0,error:`Sync failed: ${o instanceof Error?o.message:String(o)}`}}return{pushed:s.pushedFiles.slice().sort(),pulled:s.pulledFiles.slice().sort(),remoteDeleted:s.remoteDeletedFiles.slice().sort(),localDeleted:s.localDeletedFiles.slice().sort(),skippedConflicts:s.skippedConflicts.slice().sort(),hasError:s.hasError,error:s.hasError?Kg(s):void 0}}function Kg(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 Ll=N(lt());function Qg(r){let e=Number.parseInt(r,10);if(!Number.isFinite(e)||e<0||String(e)!==r.trim())throw new Ll.InvalidArgumentError("--timeout must be a non-negative integer (milliseconds).");return e}async function Zg(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??O();if(!n.getActiveProfile())return{ready:!1,error:L};let s=`${C(r)}_readiness-check`,o=Date.now();for(;Date.now()-o<t;){try{if((await n.authedRealmFetch(s,{method:"GET",headers:{Accept:"application/vnd.api+json"}})).ok)return{ready:!0}}catch{}let a=t-(Date.now()-o);if(a<=0)break;await new Promise(l=>setTimeout(l,Math.min(1e3,a)))}return{ready:!1,error:`Realm not ready after ${t}ms: ${s}`}}function Il(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)",Qg).action(async e=>{let t;try{t=await Zg(e.realm,{timeoutMs:e.timeout})}catch(n){console.error(`${y}Error:${m} ${n instanceof Error?n.message:String(n)}`),process.exit(1)}t.ready?console.log(`${_}Realm is ready.${m}`):(console.error(`${y}Error:${m} ${t.error??"Realm not ready"}`),process.exit(1))})}var Dn=N(lt()),Dl=N(require("fs/promises")),Ze=N(require("path"));var Ee=N(require("fs/promises")),Nl=N(require("path")),ey=".boxel-watch.lock";function In(r){return Nl.join(r,ey)}function ty(r){try{return process.kill(r,0),!0}catch(e){return e?.code==="EPERM"}}async function ry(r){try{let e=await Ee.readFile(In(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 Ml(r,e){await Ee.mkdir(r,{recursive:!0});let t=await ry(r),n=!1;if(t&&ty(t.pid))return{ok:!1,existing:t};t&&(n=!0);let i={pid:process.pid,startedAt:new Date().toISOString(),realmUrl:e};return await Ee.writeFile(In(r),JSON.stringify(i,null,2)+`
87
- `),{ok:!0,staleOverwrote:n}}async function Kt(r){try{await Ee.unlink(In(r))}catch(e){if(e?.code!=="ENOENT")throw e}}var Nn=class extends se{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 B(e.localDir),this.name=oy(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[s,o]of Object.entries(n.data?.attributes?.mtimes??{}))i.set(s.replace(this.normalizedRealmUrl,""),o);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 xe(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(F(n))continue;let s=this.lastKnownMtimes.get(n);s===void 0?this.recordPending(n,{status:"added",mtime:i})&&(t=!0):i>s&&this.recordPending(n,{status:"modified",mtime:i})&&(t=!0)}for(let n of this.lastKnownMtimes.keys())F(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[o,a]of e)if(a.status==="deleted"){let l=Ze.join(this.options.localDir,o);try{await Dl.unlink(l)}catch(u){if(u.code!=="ENOENT")throw u}n.push(o),i.push({file:o,status:"deleted"})}else{let l=Ze.join(this.options.localDir,o);await this.downloadFile(o,l),t.push(o),i.push({file:o,status:a.status})}for(let[o,a]of e)a.status==="deleted"?this.lastKnownMtimes.delete(o):this.lastKnownMtimes.set(o,a.mtime);await this.persistManifest(t,n);let s=await this.checkpointManager.createCheckpoint("remote",i);return{pulled:t,deleted:n,checkpoint: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(`${y}[${this.name}] Error applying changes:${m}`,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 xe(this.options.localDir),i=n?.files?{...n.files}:{};for(let a of t)delete i[a];for(let a of e){let l=Ze.join(this.options.localDir,a);try{i[a]=await fe(l)}catch(u){if(u.code!=="ENOENT")throw u}}let s={};for(let[a,l]of this.lastKnownMtimes)l!==0&&(s[a]=l);let o={realmUrl:this.normalizedRealmUrl,files:i};Object.keys(s).length>0&&(o.remoteMtimes=s),await Ne(this.options.localDir,o)}};async function ny(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 s;if(e.authenticator)s=e.authenticator;else{let d=ye({realmUrl:r[0].realmUrl,realmSecretSeed:e.realmSecretSeed,profileManager:e.profileManager});if(!d.ok)return{watchers:[],error:d.error};s=d.authenticator}let o=[];for(let d of r){let p=await Ml(d.localDir,d.realmUrl);if(!p.ok){for(let g of o)await Kt(g);return{watchers:[],error:iy(d.localDir,p.existing)}}p.staleOverwrote&&!i&&console.log(`${E}[${Mn()}] overwrote stale lock at ${d.localDir}${m}`),o.push(d.localDir)}let a=[];for(let d of r){let p=new Nn(d,s,{debounceMs:n});try{await p.initialize()}catch(g){for(let S of a)S.shutdown();for(let S of o)await Kt(S);return{watchers:[],error:`Failed to initialize watch on ${d.realmUrl}: ${g instanceof Error?g.message:String(g)}`}}a.push(p)}if(!i){console.log(`${T}\u21C5 Watching ${a.length} realm${a.length>1?"s":""}:${m}`);for(let d of a)console.log(` ${d.name} ${E}\u2192${m} ${d.localDir}`);console.log(` ${E}Interval: ${t/1e3}s, Debounce: ${n/1e3}s${m}`),console.log(` ${E}Press Ctrl+C to stop${m}
88
- `)}let l=async()=>{await Promise.all(a.map(async d=>{try{await d.poll()&&(i||console.log(`${E}[${Mn()}]${m} [${d.name}] ${P}\u26A1 ${d.pendingCount} change(s) detected${m}`),d.scheduleFlush(g=>{i||sy(d.name,g)}))}catch(p){console.error(`${y}[${d.name}] poll error:${m}`,p instanceof Error?p.message:p)}}))},u=!1,c=null,f=()=>{u||(c=setTimeout(async()=>{c=null,!u&&(await l(),f())},t))};return await l(),f(),await new Promise(d=>{let p=null,g=null,S=async()=>{if(!u){u=!0,c!==null&&(clearTimeout(c),c=null);for(let z of a)z.shutdown();p&&process.off("SIGINT",p),g&&process.off("SIGTERM",g);for(let z of o)try{await Kt(z)}catch{}d()}};if(e.signal){if(e.signal.aborted){S();return}e.signal.addEventListener("abort",()=>void S(),{once:!0})}else p=()=>{i||console.log(`
89
- ${T}\u21C5 Watch stopped${m}`),S()},g=p,process.on("SIGINT",p),process.on("SIGTERM",g)}),{watchers:a}}function iy(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 ${Ze.join(r,".boxel-watch.lock")} if it's stale.`}function sy(r,e){let t=e.pulled.length+e.deleted.length;if(t!==0&&(console.log(`${E}[${Mn()}]${m} [${r}] ${_}applied ${t} change(s)${m} (${e.pulled.length} pulled, ${e.deleted.length} deleted)`),e.checkpoint)){let n=e.checkpoint.isMajor?"[MAJOR]":"[minor]";console.log(` ${E}Checkpoint:${m} ${e.checkpoint.shortHash} ${n} ${e.checkpoint.message}`)}}function oy(r){return r.replace(/\/$/,"").split("/").slice(-2).join("/")}function Mn(){return new Date().toLocaleTimeString()}function ay(r){return e=>{let t=Number.parseFloat(e);if(!Number.isFinite(t)||t<=0)throw new Dn.InvalidArgumentError(`${r} must be a positive number.`);return t}}function ly(r){return e=>{let t=Number.parseFloat(e);if(!Number.isFinite(t)||t<0)throw new Dn.InvalidArgumentError(`${r} must be a non-negative number.`);return t}}function Fl(r){r.command("watch").description("Watch 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",ay("--interval"),30).option("-d, --debounce <seconds>","Seconds to wait after a burst of changes before applying them",ly("--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 pe(n.realmSecretSeed===!0),s=await ny([{realmUrl:e,localDir:t}],{intervalMs:n.interval*1e3,debounceMs:n.debounce*1e3,realmSecretSeed:i});s.error&&(console.error(`${y}Error:${m} ${s.error}`),process.exit(1))})}function Ul(r){let e=r.command("realm").description("Manage realms on the realm server");wi(e),vi(e),qi(e),Vi(e),vl(e),xl(e),Ol(e),Pl(e),Il(e),Fl(e)}async function cy(r,e,t){let n=t?.profileManager??O();if(!n.getActiveProfile())return{ok:!1,error:L};if(F(e))return{ok:!1,error:`Cannot delete protected file: ${e}`};let s=new URL(e,C(r)).href,o;try{o=await n.authedRealmFetch(s,{method:"DELETE",headers:{Accept:"application/vnd.card+source"}})}catch(a){return{ok:!1,error:a instanceof Error?a.message:String(a)}}if(!o.ok){let a=await o.text().catch(()=>"(no body)");return{ok:!1,error:`HTTP ${o.status}: ${a.slice(0,300)}`}}return{ok:!0}}function jl(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 cy(t.realm,e)}catch(i){console.error(`${y}Error:${m} ${i instanceof Error?i.message:String(i)}`),process.exit(1)}t.json?M.output(JSON.stringify(n,null,2)):n.ok?console.log(`${E}Deleted:${m} ${e}`):console.error(`${y}Error:${m} ${n.error}`),n.ok||process.exit(1)})}async function Fn(r,e){let t=e?.profileManager??O();if(!t.getActiveProfile())return{filenames:[],error:L};let i=C(r),s=`${i}_mtimes`;try{let o=await t.authedRealmFetch(s,{method:"GET",headers:{Accept:"application/vnd.api+json"}});if(!o.ok){let c=await o.text().catch(()=>"(no body)");return{filenames:[],error:`_mtimes returned HTTP ${o.status}: ${c.slice(0,300)}`}}let a=await o.json(),l=a?.data?.attributes?.mtimes??a,u=[];for(let c of Object.keys(l)){if(!c.startsWith(i))continue;let f=c.slice(i.length);!f||f.endsWith("/")||u.push(f)}return{filenames:u.sort()}}catch(o){return{filenames:[],error:o instanceof Error?o.message:String(o)}}}function ql(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 Fn(e.realm)}catch(n){console.error(`${y}Error:${m} ${n instanceof Error?n.message:String(n)}`),process.exit(1)}if(e.json)M.output(JSON.stringify(t,null,2)),t.error&&process.exit(1);else if(t.error)console.error(`${y}Error:${m} ${t.error}`),process.exit(1);else{for(let n of t.filenames)console.log(`${E}${n}${m}`);console.log(`
90
- ${E}${t.filenames.length} file(s)${m}`)}})}var Qt=require("fs");var Vl=require("fs");async function tt(r,e,t,n){let i=n?.profileManager??O();if(!i.getActiveProfile())return{ok:!1,error:L};let o=new URL(e,C(r)).href;try{let a=await i.authedRealmFetch(o,{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 et(r){process.stderr.write(r+`
91
- `)}async function uy(){let r=[];for await(let e of process.stdin)r.push(e);return Buffer.concat(r).toString("utf-8")}function Gl(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,Vl.readFileSync)(t.file,"utf-8")}catch(s){et(`${y}Error:${m} Could not read file: ${s instanceof Error?s.message:String(s)}`),process.exit(1)}else process.stdin.isTTY&&et(`${E}Reading from STDIN. Type or paste content, then press Enter followed by Ctrl+D to finish.${m}`),n=await uy(),et(`${E}Received ${n.length} bytes. Writing to realm...${m}`);let i;try{i=await tt(t.realm,e,n)}catch(s){et(`${y}Error:${m} ${s instanceof Error?s.message:String(s)}`),process.exit(1)}t.json?M.output(JSON.stringify(i,null,2)):i.ok?console.log(`${_}Written:${m} ${e} ${E}\u2192${m} ${t.realm}`):et(`${y}Error:${m} ${i.error}`),i.ok||process.exit(1)})}async function fy(r,e,t,n){let i=n?.profileManager??O();if(!i.getActiveProfile())return{ok:!1,error:L};let o=`${C(r)}_lint`;try{let a=await i.authedRealmFetch(o,{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 Hl(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=O();n.getActiveProfile()||(console.error(`${y}Error:${m} ${L}`),process.exit(1));let s;if(t.file)try{s=(0,Qt.readFileSync)(t.file,"utf-8")}catch(c){console.error(`${y}Error:${m} Could not read local file: ${c instanceof Error?c.message:String(c)}`),process.exit(1)}else{let c=new URL(e,C(t.realm)).href;try{let f=await n.authedRealmFetch(c,{method:"GET",headers:{Accept:"application/vnd.card+source"}});if(!f.ok){let d=await f.text().catch(()=>"(no body)");console.error(`${y}Error:${m} Could not read file from realm: HTTP ${f.status}: ${d.slice(0,300)}`),process.exit(1)}s=await f.text()}catch(f){console.error(`${y}Error:${m} ${f instanceof Error?f.message:String(f)}`),process.exit(1)}}let o;try{o=await fy(t.realm,s,e,{profileManager:n})}catch(c){console.error(`${y}Error:${m} ${c instanceof Error?c.message:String(c)}`),process.exit(1)}if(t.json){M.output(JSON.stringify(o,null,2)),o.ok||process.exit(1);return}if(o.ok||(console.error(`${y}Error:${m} ${o.error}`),process.exit(1)),t.fix&&o.fixed&&o.output)if(t.file)(0,Qt.writeFileSync)(t.file,o.output,"utf-8"),console.log(`${_}Fixed:${m} ${t.file}`);else{let c=await tt(t.realm,e,o.output,{profileManager:n});c.ok||(console.error(`${y}Error:${m} Could not write fixed file: ${c.error}`),process.exit(1)),console.log(`${_}Fixed:${m} ${e} ${E}\u2192${m} ${t.realm}`)}let a=o.messages??[],l=a.filter(c=>c.severity===2),u=a.filter(c=>c.severity===1);if(a.length===0){console.log(`${E}No lint issues found.${m}`);return}for(let c of a){let f=c.severity===2?y:P,d=c.severity===2?"error":"warning",p=c.ruleId?` (${c.ruleId})`:"";console.log(`${f}${d}${m} ${c.line}:${c.column} ${c.message}${E}${p}${m}`)}console.log(`
92
- ${E}${l.length} error(s), ${u.length} warning(s)${m}`),l.length>0&&process.exit(1)})}async function Un(r,e,t){let n=t?.profileManager??O();if(!n.getActiveProfile())return{ok:!1,error:L};let s=new URL(e,C(r)).href,o;try{o=await n.authedRealmFetch(s,{method:"GET",headers:{Accept:"application/vnd.card+source"}})}catch(l){return{ok:!1,error:l instanceof Error?l.message:String(l)}}if(!o.ok){let l=await o.text().catch(()=>"(no body)");return{ok:!1,status:o.status,error:`HTTP ${o.status}: ${l.slice(0,300)}`}}let a=await o.text();return{ok:!0,status:o.status,content:a}}function Wl(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 Un(t.realm,e)}catch(i){console.error(`${y}Error:${m} ${i instanceof Error?i.message:String(i)}`),process.exit(1)}t.json?M.output(JSON.stringify(n,null,2)):n.ok?M.output(n.content??""):(console.error(`${E}Status:${m} ${n.status??"(no status)"}`),console.error(`${y}Error:${m} ${n.error}`)),n.ok||process.exit(1)})}var jn="// touched for re-index";async function my(r,e,t){let n=t?.profileManager??O();if(!n.getActiveProfile())return{ok:!1,touched:[],skipped:[],error:L};let s;if(t?.all){if(e.length>0)return{ok:!1,touched:[],skipped:[],error:"Cannot pass file paths together with --all"};let l=await Fn(r,{profileManager:n});if(l.error)return{ok:!1,touched:[],skipped:[],error:l.error};s=l.filenames.filter(u=>(u.endsWith(".json")||u.endsWith(".gts"))&&!F(u))}else{if(e.length===0)return{ok:!1,touched:[],skipped:[],error:"No file paths provided. Pass paths or use --all."};s=e}let o=[],a=[];for(let l of s){if(!l.endsWith(".json")&&!l.endsWith(".gts")){a.push({path:l,reason:"unsupported extension"});continue}if(F(l)){a.push({path:l,reason:"protected file"});continue}let u=await Un(r,l,{profileManager:n});if(!u.ok||u.content==null){a.push({path:l,reason:u.error??"read failed"});continue}if(t?.dryRun){o.push(l);continue}let c=l.endsWith(".json")?dy(u.content):hy(u.content),f=await tt(r,l,c,{profileManager:n});if(!f.ok){a.push({path:l,reason:f.error??"write failed"});continue}o.push(l)}return{ok:a.length===0,touched:o,skipped:a}}function dy(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)+`
93
- `}catch{}return py(r)}function py(r){return r.endsWith(`
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(`
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(`
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)+`
109
+ `}catch{}return qw(r)}function qw(r){return r.endsWith(`
94
110
 
95
111
  `)?r.slice(0,-1):r+`
96
- `}function hy(r){let e=`
97
- ${jn}
112
+ `}function Gw(r){let e=`
113
+ ${fi}
98
114
  `;return r.endsWith(e)?r.slice(0,-e.length)+`
99
115
  `:r.endsWith(`
100
- `)?r+jn+`
116
+ `)?r+fi+`
101
117
  `:r+`
102
- `+jn+`
103
- `}function Bl(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 my(t.realm,e,{all:t.all,dryRun:t.dryRun})}catch(i){console.error(`${y}Error:${m} ${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(`${y}Error:${m} ${n.error}`);else{let i=t.dryRun?`${E}[dry-run]${m} `:"";for(let o of n.touched)console.log(`${i}${_}touched${m} ${o}`);for(let{path:o,reason:a}of n.skipped)console.log(`${y}skipped${m} ${o} ${E}(${a})${m}`);let s=t.dryRun?"would touch":"touched";console.log(`
104
- ${E}${s} ${n.touched.length} file(s)${n.skipped.length>0?`, skipped ${n.skipped.length}`:""}${m}`)}n.ok||process.exit(1)})}function Yl(r){let e=r.command("file").description("Read, write, search, and manage files in a realm");jl(e),ql(e),Hl(e),Wl(e),Bl(e),Gl(e)}async function gy(r,e,t){let n=t?.profileManager??O(),i=n.getActiveProfile();if(!i)throw new Error("No active profile. Run `boxel profile add` to create one.");let o=`${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(o,{method:"POST",headers:{"Content-Type":"application/vnd.api+json",Accept:"application/vnd.api+json"},body:JSON.stringify(a)})}catch(f){return{status:"error",error:`run-command fetch failed: ${f instanceof Error?f.message:String(f)}`}}if(!l.ok){let f=await l.text().catch(()=>"(no body)");return{status:"error",error:`run-command HTTP ${l.status}: ${f}`}}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 Xl(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 s=JSON.parse(t.input);(typeof s!="object"||s===null||Array.isArray(s))&&(console.error(`${y}Error:${m} --input must be a JSON object, got ${Array.isArray(s)?"array":typeof s}`),process.exit(1)),n=s}catch{console.error(`${y}Error:${m} --input is not valid JSON: ${t.input}`),process.exit(1)}let i;try{i=await gy(e,t.realm,{input:n})}catch(s){console.error(`${y}Error:${m} ${s instanceof Error?s.message:String(s)}`),process.exit(1)}if(t.json)M.output(JSON.stringify(i,null,2));else{if(console.log(`${E}Status:${m} ${yy(i.status)}${i.status}${m}`),i.result){console.log(`${E}Result:${m}`);try{M.output(JSON.stringify(JSON.parse(i.result),null,2))}catch{M.output(i.result)}}i.error&&console.error(`${y}Error:${m} ${i.error}`)}(i.status==="error"||i.status==="unusable")&&process.exit(1)})}function yy(r){switch(r){case"ready":return _;case"error":return y;default:return T}}async function Ey(r,e,t){let n=t?.profileManager??O(),i=n.getActiveProfile();if(!i)return{ok:!1,error:L};let o=`${i.profile.realmServerUrl.replace(/\/$/,"")}/_federated-search`,a=(Array.isArray(r)?r:[r]).map(C);try{let l=await n.authedRealmServerFetch(o,{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 zl(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(`${y}Error:${m} 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(`${y}Error:${m} --query must be a JSON object, got ${Array.isArray(i)?"array":typeof i}`),process.exit(1)),t=i}catch(i){console.error(`${y}Error:${m} Invalid JSON in --query: ${i instanceof Error?i.message:String(i)}`),process.exit(1);return}let n;try{n=await Ey(e.realm,t)}catch(i){console.error(`${y}Error:${m} ${i instanceof Error?i.message:String(i)}`),process.exit(1);return}e.json?M.output(JSON.stringify(n,null,2)):n.ok?M.output(JSON.stringify(n.data??[],null,2)):(console.error(`${E}Status:${m} ${n.status??"(no status)"}`),console.error(`${y}Error:${m} ${n.error}`)),n.ok||process.exit(1)})}function Kl(r){let e=new Jl.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&&ht(!0)}),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",`
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",`
105
121
  Environment variables (for 'add'):
106
122
  BOXEL_PASSWORD Password; preferred over -p to avoid shell history.
107
123
  BOXEL_ENVIRONMENT An env-mode slug (e.g. a branch name), interpreted
108
124
  like scripts/env-slug.sh: URLs are derived as
109
125
  http://matrix.<slug>.localhost and
110
126
  http://realm-server.<slug>.localhost/. Overridden
111
- 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 yi(t,n,i)}),Yl(e),Ul(e),Xl(e),zl(e),Ei(e),e}var wy=JSON.parse((0,Ql.readFileSync)((0,Zl.resolve)(__dirname,"../package.json"),"utf-8"));process.argv.includes("--quiet")&&ht(!0);Kl(wy.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")&&Zt(!0);jc(Bw.version).parse();
112
128
  /*! Bundled license information:
113
129
 
114
130
  safe-buffer/index.js: