@cardstack/boxel-cli 0.1.3 → 0.1.4

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