@fnet/cli 0.131.2 → 0.133.0

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.
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import e from"chalk";import o from"yargs";import{hideBin as t}from"yargs/helpers";import n from"node:path";import s from"node:fs";import l from"node:os";import r from"@fnet/prompt";import{fileURLToPath as i}from"node:url";import a from"cli-table3";import{promisify as c}from"node:util";import m from"tree-kill";function d(){return n.join(l.homedir(),".fnet","bin")}function h(){return n.join(l.homedir(),".fnet","metadata")}function u(){return n.join(h(),"binaries.json")}function f(){try{if("win32"===process.platform)return process.env.PSModulePath&&process.env.PSModulePath.includes("PowerShell")?"powershell-core":process.env.PSModulePath?"powershell":"cmd";const e=process.env.SHELL||"";return e.includes("bash")?"bash":e.includes("zsh")?"zsh":e.includes("fish")?"fish":e.includes("ksh")?"ksh":e.includes("csh")||e.includes("tcsh")?"csh":s.existsSync(n.join(l.homedir(),".bashrc"))?"bash":s.existsSync(n.join(l.homedir(),".zshrc"))?"zsh":s.existsSync(n.join(l.homedir(),".config","fish","config.fish"))?"fish":"unknown"}catch(e){return"unknown"}}function p(e){const o=l.homedir(),t=[];switch(e){case"bash":t.push({name:".bashrc",path:n.join(o,".bashrc")}),t.push({name:".bash_profile",path:n.join(o,".bash_profile")}),t.push({name:".profile",path:n.join(o,".profile")});break;case"zsh":t.push({name:".zshrc",path:n.join(o,".zshrc")}),t.push({name:".zprofile",path:n.join(o,".zprofile")});break;case"fish":t.push({name:"config.fish",path:n.join(o,".config","fish","config.fish")});break;case"ksh":t.push({name:".kshrc",path:n.join(o,".kshrc")}),t.push({name:".profile",path:n.join(o,".profile")});break;case"csh":t.push({name:".cshrc",path:n.join(o,".cshrc")}),t.push({name:".tcshrc",path:n.join(o,".tcshrc")});break;case"powershell":t.push({name:"Microsoft.PowerShell_profile.ps1",path:n.join(o,"Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1")}),t.push({name:"profile.ps1",path:n.join(o,"Documents","WindowsPowerShell","profile.ps1")});break;case"powershell-core":t.push({name:"Microsoft.PowerShell_profile.ps1",path:n.join(o,"Documents","PowerShell","Microsoft.PowerShell_profile.ps1")}),t.push({name:"profile.ps1",path:n.join(o,"Documents","PowerShell","profile.ps1")});break;case"cmd":t.push({name:"fnet-path.bat",path:n.join(o,"fnet-path.bat")})}return t}function y(e,o){switch(e){case"bash":case"zsh":case"ksh":default:return`export PATH="${o}:$PATH"`;case"fish":return`set -gx PATH ${o} $PATH`;case"csh":return`setenv PATH ${o}:$PATH`;case"powershell":case"powershell-core":return`$env:PATH = "${o};" + $env:PATH`;case"cmd":return`@echo off\nSETX PATH "%PATH%;${o}"\necho Path updated successfully`}}var g={getBinDirectory:d,getMetadataDirectory:h,getMetadataFilePath:u,checkIfInPath:function(e){return(process.env.PATH||"").split(n.delimiter).includes(e)},detectUserShell:f,getShellConfigPath:function(){const e=p(f());for(const o of e)if(s.existsSync(o.path))return o.path;return e.length>0?e[0].path:null},getAllShellConfigPaths:p,createBinDirectoryStructure:async function(){const e=d(),o=h(),t=u();s.existsSync(e)||s.mkdirSync(e,{recursive:!0}),s.existsSync(o)||s.mkdirSync(o,{recursive:!0}),s.existsSync(t)||s.writeFileSync(t,JSON.stringify({binaries:{},lastUpdated:(new Date).toISOString()},null,2))},getExportPathCommand:y,addBinToPath:async function(o,t,l){try{const r=y(o,l);if("cmd"===o)return s.writeFileSync(t,r),console.log(e.yellow(`Created batch file at ${t}`)),console.log(e.yellow("Run this file to add the bin directory to your PATH")),!0;if("powershell"!==o&&"powershell-core"!==o||s.existsSync(n.dirname(t))||s.mkdirSync(n.dirname(t),{recursive:!0}),!s.existsSync(t)){const n="fish"===o?"# Fish shell configuration\n\n":"powershell"===o||"powershell-core"===o?"# PowerShell profile\n\n":"# Shell configuration\n\n";s.writeFileSync(t,n),console.log(e.green(`Created config file at ${t}`))}const i=s.readFileSync(t,"utf8");if(i.includes(l))return!0;const a=`${i.trim()}\n\n# Added by @fnet/cli\n${r}\n`;return s.writeFileSync(t,a),"powershell"!==o&&"powershell-core"!==o||(console.log(e.yellow("You may need to set the PowerShell execution policy to run scripts:")),console.log(e.green("Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned"))),!0}catch(o){return console.error(e.red(`Failed to add bin directory to PATH: ${o.message}`)),!1}}};async function w(e){const o=function(){const e=l.homedir(),o=n.join(e,".fnet","bin");return s.existsSync(o)||s.mkdirSync(o,{recursive:!0}),o}(),t=function(){const e=l.homedir(),o=n.join(e,".fnet");return s.existsSync(o)||s.mkdirSync(o,{recursive:!0}),n.join(o,"bin-registry.json")}();let r={};if(s.existsSync(t))try{const e=s.readFileSync(t,"utf8");r=JSON.parse(e)}catch(e){console.warn(`Warning: Could not parse bin registry: ${e.message}`)}return{binDir:o,registryPath:t,registry:r,args:e}}n.dirname(i(import.meta.url));var b={command:"setup",describe:"Initialize the bin system",builder:{},handler:async o=>{try{await w(o);console.log(e.blue("Setting up the bin system...")),await g.createBinDirectoryStructure();const t=g.getBinDirectory();console.log(e.green(`Bin directory: ${t}`));if(g.checkIfInPath(t))console.log(e.green("Bin directory is already in PATH."));else{console.log(e.yellow("Bin directory is not in PATH."));const{confirmAddToPath:o}=await r({type:"confirm",name:"confirmAddToPath",message:`Would you like to add ${t} to your PATH?`,initial:!0});if(o){let o=g.detectUserShell();if("unknown"===o){const{selectedShell:e}=await r({type:"select",name:"selectedShell",message:"Select your shell:",choices:[{name:"bash",message:"Bash"},{name:"zsh",message:"Zsh"},{name:"fish",message:"Fish"},{name:"powershell",message:"PowerShell"},{name:"powershell-core",message:"PowerShell Core"},{name:"cmd",message:"Windows Command Prompt"},{name:"ksh",message:"Korn Shell (ksh)"},{name:"csh",message:"C Shell (csh/tcsh)"}]});o=e}else{const{confirmShell:e}=await r({type:"confirm",name:"confirmShell",message:`Detected shell: ${o}. Is this correct?`,initial:!0});if(!e){const{selectedShell:e}=await r({type:"select",name:"selectedShell",message:"Select your shell:",choices:[{name:"bash",message:"Bash"},{name:"zsh",message:"Zsh"},{name:"fish",message:"Fish"},{name:"powershell",message:"PowerShell"},{name:"powershell-core",message:"PowerShell Core"},{name:"cmd",message:"Windows Command Prompt"},{name:"ksh",message:"Korn Shell (ksh)"},{name:"csh",message:"C Shell (csh/tcsh)"}]});o=e}}const i=g.getAllShellConfigPaths(o);let a;if(i.length>1){const e=i.filter((e=>s.existsSync(e.path)));if(e.length>0){const{selectedConfigPath:o}=await r({type:"select",name:"selectedConfigPath",message:"Select the configuration file to modify:",choices:e.map((e=>({name:e.path,message:`${e.name} (${e.path})`})))});a=o}else{const{selectedConfigPath:e}=await r({type:"select",name:"selectedConfigPath",message:"Select the configuration file to create:",choices:i.map((e=>({name:e.path,message:`${e.name} (${e.path})`})))});a=e}}else if(1===i.length)a=i[0].path;else{const{enteredConfigPath:e}=await r({type:"input",name:"enteredConfigPath",message:"Enter the path to your shell configuration file:",initial:n.join(l.homedir(),".bashrc")});a=e}await g.addBinToPath(o,a,t)?(console.log(e.green(`Added bin directory to PATH in ${a}`)),console.log(e.yellow("Please restart your terminal or run the following command:")),console.log(e.green(`source ${a}`))):(console.log(e.red(`Failed to add bin directory to PATH in ${a}`)),console.log(e.yellow("You can add it manually by adding the following line to your shell configuration:")),console.log(e.green(g.getExportPathCommand(o,t))))}else console.log(e.yellow("You can add it manually by adding the following line to your shell configuration:")),console.log(e.green(`export PATH="${t}:$PATH"`)),console.log(e.yellow("Or run:")),console.log(e.green("fbin path"))}console.log(e.green("Bin system setup completed successfully."))}catch(o){console.error(e.red(`Failed to set up bin system: ${o.message}`)),process.exit(1)}}};var S={command:"path",describe:"Add bin directory to PATH",builder:{yes:{describe:"Automatically answer yes to all prompts",type:"boolean",default:!1,alias:"y"}},handler:async o=>{try{await w(o);const t=g.getBinDirectory();console.log(e.blue(`Adding ${t} to PATH...`)),g.createBinDirectoryStructure()||(console.log(e.yellow("Creating bin directory structure...")),await g.createBinDirectoryStructure());if(g.checkIfInPath(t))return void console.log(e.green("Bin directory is already in PATH."));let i=g.detectUserShell();if("unknown"===i)if(o.yes)i="win32"===process.platform?"powershell":"bash",console.log(e.yellow(`Auto-selecting ${i} shell due to --yes flag`));else{const{selectedShell:e}=await r({type:"select",name:"selectedShell",message:"Select your shell:",choices:[{name:"bash",message:"Bash"},{name:"zsh",message:"Zsh"},{name:"fish",message:"Fish"},{name:"powershell",message:"PowerShell"},{name:"powershell-core",message:"PowerShell Core"},{name:"cmd",message:"Windows Command Prompt"},{name:"ksh",message:"Korn Shell (ksh)"},{name:"csh",message:"C Shell (csh/tcsh)"}]});i=e}else if(o.yes)console.log(e.yellow(`Auto-confirming detected shell: ${i} due to --yes flag`));else{const{confirmShell:e}=await r({type:"confirm",name:"confirmShell",message:`Detected shell: ${i}. Is this correct?`,initial:!0});if(!e){const{selectedShell:e}=await r({type:"select",name:"selectedShell",message:"Select your shell:",choices:[{name:"bash",message:"Bash"},{name:"zsh",message:"Zsh"},{name:"fish",message:"Fish"},{name:"powershell",message:"PowerShell"},{name:"powershell-core",message:"PowerShell Core"},{name:"cmd",message:"Windows Command Prompt"},{name:"ksh",message:"Korn Shell (ksh)"},{name:"csh",message:"C Shell (csh/tcsh)"}]});i=e}}const a=g.getAllShellConfigPaths(i);let c;if(a.length>1){const t=a.filter((e=>s.existsSync(e.path)));if(t.length>0)if(o.yes)c=t[0].path,console.log(e.yellow(`Auto-selecting config file: ${c} due to --yes flag`));else{const{selectedConfigPath:e}=await r({type:"select",name:"selectedConfigPath",message:"Select the configuration file to modify:",choices:t.map((e=>({name:e.path,message:`${e.name} (${e.path})`})))});c=e}else if(o.yes)c=a[0].path,console.log(e.yellow(`Auto-selecting config file to create: ${c} due to --yes flag`));else{const{selectedConfigPath:e}=await r({type:"select",name:"selectedConfigPath",message:"Select the configuration file to create:",choices:a.map((e=>({name:e.path,message:`${e.name} (${e.path})`})))});c=e}}else if(1===a.length)c=a[0].path;else if(o.yes)c=n.join(l.homedir(),"win32"===process.platform?"_profile":".bashrc"),console.log(e.yellow(`Auto-selecting default config file: ${c} due to --yes flag`));else{const{enteredConfigPath:e}=await r({type:"input",name:"enteredConfigPath",message:"Enter the path to your shell configuration file:",initial:n.join(l.homedir(),".bashrc")});c=e}await g.addBinToPath(i,c,t)?(console.log(e.green(`Added bin directory to PATH in ${c}`)),console.log(e.yellow("Please restart your terminal or run the following command:")),console.log(e.green(`source ${c}`))):(console.log(e.red(`Failed to add bin directory to PATH in ${c}`)),console.log(e.yellow("You can add it manually by adding the following line to your shell configuration:")),console.log(e.green(g.getExportPathCommand(i,t))))}catch(o){console.error(e.red(`Failed to add bin directory to PATH: ${o.message}`)),process.exit(1)}}};var P={command:"compile [source] [options]",describe:"Compile a CLI project to a binary",builder:{source:{describe:"Source file to compile",type:"string",default:"./dist/cli/esm/index.js"},output:{describe:"Output file name",type:"string",alias:"o"},name:{describe:"Binary name",type:"string",alias:"n"},force:{describe:"Force overwrite if binary already exists",type:"boolean",default:!1,alias:"f"},target:{describe:"Target platform (auto, linux, macos, windows)",type:"string",choices:["auto","linux","macos","windows"],default:"auto"},minify:{describe:"Minify the output binary",type:"boolean",default:!0},external:{describe:"External packages to exclude from the bundle (comma-separated)",type:"string"}},handler:async o=>{try{await w(o);const t=process.cwd(),l=n.basename(t),i=o.name||l;let a;if(o.output)a=o.output;else{const e=n.join(t,".bin");s.existsSync(e)||s.mkdirSync(e,{recursive:!0}),a=n.join(e,i)}const c=n.resolve(process.cwd(),o.source);if(s.existsSync(c)||(console.error(e.red(`Source file not found: ${c}`)),console.error(e.yellow("Make sure to build your project first.")),process.exit(1)),s.existsSync(a)&&!o.force){const{confirmOverwrite:o}=await r({type:"confirm",name:"confirmOverwrite",message:`Binary already exists at ${a}. Overwrite?`,initial:!1});if(!o)return void console.log(e.yellow("Compilation cancelled."))}const m=process.platform;console.log(e.blue(`Detected platform: ${m}`)),"win32"!==m||a.endsWith(".exe")||(a=`${a}.exe`,console.log(e.blue(`Adjusted output path for Windows: ${a}`))),console.log(e.blue(`Compiling ${c} to ${a}...`));const{spawn:d}=await import("child_process");try{const e=d("bun",["--version"],{stdio:"pipe"});await new Promise(((o,t)=>{e.on("close",(e=>{0===e?o():t(new Error("Bun is not available. Please install Bun first."))})),e.on("error",(e=>{t(new Error(`Bun is not available: ${e.message}`))}))}))}catch(o){console.error(e.red(`Bun is not available: ${o.message}`)),console.error(e.yellow("Please install Bun first: https://bun.sh/")),process.exit(1)}const h=["build",c,"--compile",`--outfile=${a}`];if(o.target&&"auto"!==o.target&&h.push(`--target=${o.target}`),!1===o.minify&&h.push("--no-minify"),o.external){o.external.split(",").map((e=>e.trim())).forEach((e=>{h.push(`--external:${e}`)}))}console.log(e.blue(`Running: bun ${h.join(" ")}`));const u=d("bun",h,{stdio:"inherit"});await new Promise(((e,o)=>{u.on("close",(t=>{0===t?e():o(new Error(`Compilation failed with code ${t}`))})),u.on("error",(e=>{o(e)}))})),"win32"!==m&&s.chmodSync(a,493),console.log(e.green(`Binary compiled successfully: ${a}`)),"win32"===m?console.log(e.yellow("Note: On Windows, you may need to run the binary from a command prompt or PowerShell.")):"darwin"===m&&console.log(e.yellow("Note: On macOS, you may need to allow the binary to run in System Preferences > Security & Privacy."))}catch(o){console.error(e.red(`Failed to compile binary: ${o.message}`)),process.exit(1)}}};var $={command:"install [source] [options]",describe:"Install a binary to the bin directory",builder:{source:{describe:"Source binary to install",type:"string",demandOption:!0},name:{describe:"Name to use for the installed binary",type:"string",alias:"n"},force:{describe:"Force overwrite if binary already exists",type:"boolean",default:!1,alias:"f"},yes:{describe:"Automatically answer yes to all prompts",type:"boolean",default:!1,alias:"y"}},handler:async o=>{try{await w(o);const t=n.resolve(process.cwd(),o.source);s.existsSync(t)||(console.error(e.red(`Source file not found: ${t}`)),process.exit(1)),await g.createBinDirectoryStructure();const l=g.getBinDirectory();let i;i=o.name?o.name:n.basename(t),"win32"!==process.platform||i.endsWith(".exe")||(i=`${i}.exe`);const a=n.join(l,i);if(s.existsSync(a)&&!o.force&&!o.yes){const{confirmOverwrite:o}=await r({type:"confirm",name:"confirmOverwrite",message:`Binary already exists at ${a}. Overwrite?`,initial:!1});if(!o)return void console.log(e.yellow("Installation cancelled."))}console.log(e.blue(`Installing ${t} to ${a}...`)),s.copyFileSync(t,a),"win32"!==process.platform&&s.chmodSync(a,493);const c=g.getMetadataFilePath();let m={binaries:{},lastUpdated:(new Date).toISOString()};if(s.existsSync(c))try{m=JSON.parse(s.readFileSync(c,"utf8"))}catch(o){console.warn(e.yellow(`Failed to parse metadata file: ${o.message}`)),console.warn(e.yellow("Creating new metadata file."))}let d="0.0.0";try{const{execSync:o}=require("child_process"),t=o(`"${a}" --version`,{timeout:5e3,stdio:["ignore","pipe","ignore"]}).toString().trim(),n=t.match(/v?(\d+\.\d+\.\d+)/);n?(d=n[1],console.log(e.blue(`Detected binary version: ${d}`))):(console.log(e.yellow(`Could not parse version from output: ${t}`)),console.log(e.yellow(`Using default version: ${d}`)))}catch(o){console.log(e.yellow(`Could not detect binary version, using default: ${d}`))}m.binaries[i]={path:a,source:t,created:(new Date).toISOString(),platform:process.platform,version:d,project:n.basename(process.cwd())},m.lastUpdated=(new Date).toISOString(),s.writeFileSync(c,JSON.stringify(m,null,2)),console.log(e.green(`Binary installed successfully: ${a}`));g.checkIfInPath(l)?console.log(e.green(`You can now run '${i}' from anywhere.`)):console.log(e.yellow("Bin directory is not in PATH. Run 'fbin path' to add it."))}catch(o){console.error(e.red(`Failed to install binary: ${o.message}`)),process.exit(1)}}};var x={promptForSelection:async function(o){const{items:t,message:n,nameField:s="name",valueField:l="name",initialValue:i=null,allowAbort:a=!0}=o;if(!t||0===t.length)return console.log(e.yellow("No items available for selection.")),null;if(1===t.length&&!a){const o=t[0],n="string"==typeof o?o:o[l];return console.log(e.blue(`Only one option available: ${"string"==typeof o?o:o[s]}`)),n}let c=t.map((e=>"string"==typeof e?{name:e,value:e,message:e}:{name:e[l],value:e[l],message:e[s]||e[l]}));a&&c.push({name:"cancel",value:null,message:e.yellow("Cancel")});let m=null;if(i){const e=c.findIndex((e=>e.name===i));-1!==e&&(m=e)}const d="selectedItem",{[d]:h}=await r({type:"select",name:d,message:n,choices:c,initial:m});return"cancel"===h?null:h},promptForMultipleSelection:async function(o){const{items:t,message:n,nameField:s="name",valueField:l="name",initialValues:i=[],allowAbort:a=!0}=o;if(!t||0===t.length)return console.log(e.yellow("No items available for selection.")),null;let c=t.map((e=>"string"==typeof e?{name:e,value:e,message:e}:{name:e[l],value:e[l],message:e[s]||e[l]})),m=[];i&&i.length>0&&(m=c.map(((e,o)=>i.includes(e.name)?o:-1)).filter((e=>-1!==e)));const d="selectedItems",h=await r({type:"multiselect",name:d,message:n,choices:c,initial:m,hint:"(Use space to select, enter to confirm)",validate:e=>!(0===e.length&&!a)||"Please select at least one item"});return a&&0===h[d].length?null:h[d]}};var v={command:"uninstall [name] [options]",describe:"Uninstall a binary from the bin directory",builder:{name:{describe:"Name of the binary to uninstall",type:"string",demandOption:!1},force:{describe:"Skip confirmation prompt",type:"boolean",default:!1,alias:"f"},yes:{describe:"Automatically answer yes to all prompts",type:"boolean",default:!1,alias:"y"}},handler:async o=>{try{await w(o);const t=g.getBinDirectory(),n=g.getMetadataFilePath();let l;s.existsSync(t)||(console.error(e.red(`Bin directory not found: ${t}`)),console.error(e.yellow("Run fbin setup first.")),process.exit(1)),s.existsSync(n)||(console.error(e.red(`Metadata file not found: ${n}`)),console.error(e.yellow("Run fbin setup first.")),process.exit(1));try{l=JSON.parse(s.readFileSync(n,"utf8"))}catch(o){console.error(e.red(`Failed to parse metadata file: ${o.message}`)),process.exit(1)}if(!o.name&&!o.yes){const t=Object.keys(l.binaries);if(0===t.length)return void console.log(e.yellow("No binaries installed."));const n=await x.promptForSelection({items:t,message:"Select a binary to uninstall:",allowAbort:!0});if(null===n)return void console.log(e.yellow("Uninstallation cancelled."));o.name=n}const i=o.name;i||(console.error(e.red("Binary name is required.")),console.error(e.yellow("Use --name to specify a binary or run without --yes to select interactively.")),process.exit(1)),l.binaries[i]||(console.error(e.red(`Binary not found in metadata: ${i}`)),console.log(e.yellow("Use fbin list to see installed binaries.")),process.exit(1));const a=l.binaries[i].path;if(s.existsSync(a)||(console.warn(e.yellow(`Binary file not found: ${a}`)),console.warn(e.yellow("Metadata will be updated anyway."))),!o.force&&!o.yes){const{confirmUninstall:o}=await r({type:"confirm",name:"confirmUninstall",message:`Are you sure you want to uninstall ${i}?`,initial:!1});if(!o)return void console.log(e.yellow("Uninstallation cancelled."))}if(s.existsSync(a))try{s.unlinkSync(a),console.log(e.green(`Binary file removed: ${a}`))}catch(o){console.error(e.red(`Failed to remove binary file: ${o.message}`))}delete l.binaries[i],l.lastUpdated=(new Date).toISOString(),s.writeFileSync(n,JSON.stringify(l,null,2)),console.log(e.green(`Binary uninstalled successfully: ${i}`))}catch(o){console.error(e.red(`Failed to uninstall binary: ${o.message}`)),process.exit(1)}}};function A(o,t={}){const n={chars:{top:"─","top-mid":"─","top-left":" ","top-right":" ",bottom:"─","bottom-mid":"─","bottom-left":" ","bottom-right":" ",left:" ","left-mid":" ",mid:"─","mid-mid":"─",right:" ","right-mid":" ",middle:" "},style:{head:[],border:[],compact:!0},wordWrap:!0,...t,head:o.map((o=>e.bold(o)))};return new a(n)}var C={createTable:A,createTableWithData:function(e,o,t={}){const n=A(e,t);return Array.isArray(o)&&o.forEach((e=>{n.push(e)})),n.toString()},getStatusColor:function(o){switch(o){case"running":return e.green;case"stopped":return e.yellow;case"failed":return e.red;case"registered":return e.blue;default:return e.gray}}};var F={command:"list [options]",describe:"List installed binaries",builder:{json:{describe:"Output in JSON format",type:"boolean",default:!1,alias:"j"},filter:{describe:"Filter binaries by name",type:"string",alias:"f"}},handler:async o=>{try{await w(o);const t=g.getBinDirectory(),n=g.getMetadataFilePath();let l;s.existsSync(t)||(console.error(e.red(`Bin directory not found: ${t}`)),console.error(e.yellow("Run fbin setup first.")),process.exit(1)),s.existsSync(n)||(console.error(e.red(`Metadata file not found: ${n}`)),console.error(e.yellow("Run fbin setup first.")),process.exit(1));try{l=JSON.parse(s.readFileSync(n,"utf8"))}catch(o){console.error(e.red(`Failed to parse metadata file: ${o.message}`)),process.exit(1)}let r=l.binaries;if(o.filter){const e=o.filter.toLowerCase();r=Object.entries(r).filter((([o])=>o.toLowerCase().includes(e))).reduce(((e,[o,t])=>(e[o]=t,e)),{})}if(o.json)return void console.log(JSON.stringify(r,null,2));const i=Object.keys(r).length;if(0===i)return void console.log(e.yellow("No binaries installed."));console.log(e.blue(`Found ${i} installed binaries:`)),console.log();const a=["NAME","VERSION","PLATFORM","CREATED"],c=C.createTable(a,{chars:{mid:"","mid-mid":"","left-mid":"","right-mid":""}});Object.entries(r).forEach((([o,t])=>{const n=new Date(t.created).toLocaleString();c.push([e.white(o),t.version||"N/A",t.platform||"N/A",n])})),console.log(c.toString()),console.log(),console.log(e.blue(`Bin directory: ${t}`));g.checkIfInPath(t)||console.log(e.yellow("Bin directory is not in PATH. Run 'fbin path' to add it."))}catch(o){console.error(e.red(`Failed to list binaries: ${o.message}`)),process.exit(1)}}};c(m);let j=!1;process.on("uncaughtException",(e=>{j||(j=!0,setTimeout((()=>process.exit(1)),500))})),process.on("unhandledRejection",(e=>{j||(j=!0,setTimeout((()=>process.exit(1)),500))})),async function(){try{o(t(process.argv)).usage("Usage: $0 <command> [options]").command(b).command(S).command(P).command($).command(v).command(F).demandCommand(1,"You need to specify a command").help().version().argv}catch(o){console.error(e.red(`Fatal error: ${o.message}`)),process.exit(1)}}().catch((o=>{console.error(e.red(`Fatal error: ${o.message}`)),process.exit(1)}));
2
+ import e from"chalk";import o from"yargs";import{hideBin as t}from"yargs/helpers";import s from"node:path";import n from"node:fs";import l from"node:os";import i from"@fnet/prompt";import{fileURLToPath as a}from"node:url";import r from"cli-table3";import{promisify as c}from"node:util";import d from"tree-kill";function m(){return s.join(l.homedir(),".fnet","bin")}function u(){return s.join(l.homedir(),".fnet","metadata")}function g(){return s.join(u(),"binaries.json")}function p(){try{if("win32"===process.platform)return process.env.PSModulePath&&process.env.PSModulePath.includes("PowerShell")?"powershell-core":process.env.PSModulePath?"powershell":"cmd";const e=process.env.SHELL||"";return e.includes("bash")?"bash":e.includes("zsh")?"zsh":e.includes("fish")?"fish":e.includes("ksh")?"ksh":e.includes("csh")||e.includes("tcsh")?"csh":n.existsSync(s.join(l.homedir(),".bashrc"))?"bash":n.existsSync(s.join(l.homedir(),".zshrc"))?"zsh":n.existsSync(s.join(l.homedir(),".config","fish","config.fish"))?"fish":"unknown"}catch(e){return"unknown"}}function f(e){const o=l.homedir(),t=[];switch(e){case"bash":t.push({name:".bashrc",path:s.join(o,".bashrc")}),t.push({name:".bash_profile",path:s.join(o,".bash_profile")}),t.push({name:".profile",path:s.join(o,".profile")});break;case"zsh":t.push({name:".zshrc",path:s.join(o,".zshrc")}),t.push({name:".zprofile",path:s.join(o,".zprofile")});break;case"fish":t.push({name:"config.fish",path:s.join(o,".config","fish","config.fish")});break;case"ksh":t.push({name:".kshrc",path:s.join(o,".kshrc")}),t.push({name:".profile",path:s.join(o,".profile")});break;case"csh":t.push({name:".cshrc",path:s.join(o,".cshrc")}),t.push({name:".tcshrc",path:s.join(o,".tcshrc")});break;case"powershell":t.push({name:"Microsoft.PowerShell_profile.ps1",path:s.join(o,"Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1")}),t.push({name:"profile.ps1",path:s.join(o,"Documents","WindowsPowerShell","profile.ps1")});break;case"powershell-core":t.push({name:"Microsoft.PowerShell_profile.ps1",path:s.join(o,"Documents","PowerShell","Microsoft.PowerShell_profile.ps1")}),t.push({name:"profile.ps1",path:s.join(o,"Documents","PowerShell","profile.ps1")});break;case"cmd":t.push({name:"fnet-path.bat",path:s.join(o,"fnet-path.bat")})}return t}function h(e,o){switch(e){case"bash":case"zsh":case"ksh":default:return`export PATH="${o}:$PATH"`;case"fish":return`set -gx PATH ${o} $PATH`;case"csh":return`setenv PATH ${o}:$PATH`;case"powershell":case"powershell-core":return`$env:PATH = "${o};" + $env:PATH`;case"cmd":return`@echo off\nSETX PATH "%PATH%;${o}"\necho Path updated successfully`}}function y(){return s.join(l.homedir(),".fnet","backups")}function b(){const e=(new Date).toISOString().replace(/:/g,"-").replace(/\..+/,""),o=s.join(y(),e);return n.existsSync(o)||n.mkdirSync(o,{recursive:!0}),o}function w(o,t,l=null){try{if(!n.existsSync(o))return!1;const e=l||s.basename(o),i=s.join(t,e),a=s.dirname(i);return n.existsSync(a)||n.mkdirSync(a,{recursive:!0}),n.copyFileSync(o,i),!0}catch(t){return console.error(e.red(`Failed to backup file ${o}: ${t.message}`)),!1}}function S(e,o={}){const t={timestamp:(new Date).toISOString(),type:o.type||"manual",message:o.message||"",command:o.command||"",files:o.files||[],...o},l=s.join(e,"metadata.json");n.writeFileSync(l,JSON.stringify(t,null,2))}function $(o){const t=s.join(y(),"latest");try{n.existsSync(t)&&n.unlinkSync(t),"win32"===process.platform?n.writeFileSync(t+".txt",o):n.symlinkSync(o,t)}catch(o){console.warn(e.yellow(`Could not create latest symlink: ${o.message}`))}}var k={getBinDirectory:m,getMetadataDirectory:u,getMetadataFilePath:g,checkIfInPath:function(e){return(process.env.PATH||"").split(s.delimiter).includes(e)},detectUserShell:p,getShellConfigPath:function(){const e=f(p());for(const o of e)if(n.existsSync(o.path))return o.path;return e.length>0?e[0].path:null},getAllShellConfigPaths:f,createBinDirectoryStructure:async function(){const e=m(),o=u(),t=g();n.existsSync(e)||n.mkdirSync(e,{recursive:!0}),n.existsSync(o)||n.mkdirSync(o,{recursive:!0}),n.existsSync(t)||n.writeFileSync(t,JSON.stringify({binaries:{},lastUpdated:(new Date).toISOString()},null,2))},getExportPathCommand:h,addBinToPath:async function(o,t,l,i={}){try{const{autoBackup:a=!0}=i,r=h(o,l);if("cmd"===o)return n.writeFileSync(t,r),console.log(e.yellow(`Created batch file at ${t}`)),console.log(e.yellow("Run this file to add the bin directory to your PATH")),!0;if("powershell"!==o&&"powershell-core"!==o||n.existsSync(s.dirname(t))||n.mkdirSync(s.dirname(t),{recursive:!0}),!n.existsSync(t)){const s="fish"===o?"# Fish shell configuration\n\n":"powershell"===o||"powershell-core"===o?"# PowerShell profile\n\n":"# Shell configuration\n\n";n.writeFileSync(t,s),console.log(e.green(`Created config file at ${t}`))}const c=n.readFileSync(t,"utf8");if(c.includes(l))return!0;if(a&&n.existsSync(t)){const o=b(),n=s.basename(t);w(t,s.join(o,"configs"),n)&&(S(o,{type:"auto",command:"addBinToPath",message:`Automatic backup before modifying ${n}`,files:[t]}),$(o),console.log(e.green(`✓ Backed up ${n} to ${o}`)))}const d=`${c.trim()}\n\n# Added by @fnet/cli\n${r}\n`;return n.writeFileSync(t,d),"powershell"!==o&&"powershell-core"!==o||(console.log(e.yellow("You may need to set the PowerShell execution policy to run scripts:")),console.log(e.green("Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned"))),!0}catch(o){return console.error(e.red(`Failed to add bin directory to PATH: ${o.message}`)),!1}},getBackupDirectory:y,createBackupDirectory:b,backupFile:w,createBackupMetadata:S,listBackups:function(){const e=y();if(!n.existsSync(e))return[];const o=[],t=n.readdirSync(e);for(const l of t){const t=s.join(e,l),i=n.statSync(t);if(i.isDirectory()&&"latest"!==l){const e=s.join(t,"metadata.json");let a={};if(n.existsSync(e))try{a=JSON.parse(n.readFileSync(e,"utf8"))}catch(e){}o.push({timestamp:l,path:t,created:i.mtime,...a})}}return o.sort(((e,o)=>new Date(o.created)-new Date(e.created))),o},updateLatestSymlink:$};async function P(e){const o=function(){const e=l.homedir(),o=s.join(e,".fnet","bin");return n.existsSync(o)||n.mkdirSync(o,{recursive:!0}),o}(),t=function(){const e=l.homedir(),o=s.join(e,".fnet");return n.existsSync(o)||n.mkdirSync(o,{recursive:!0}),s.join(o,"bin-registry.json")}();let i={};if(n.existsSync(t))try{const e=n.readFileSync(t,"utf8");i=JSON.parse(e)}catch(e){console.warn(`Warning: Could not parse bin registry: ${e.message}`)}return{binDir:o,registryPath:t,registry:i,args:e}}s.dirname(a(import.meta.url));var v={command:"setup",describe:"Initialize the bin system",builder:{yes:{describe:"Automatically answer yes to all prompts",type:"boolean",default:!1,alias:"y"}},handler:async o=>{try{await P(o);console.log(e.blue("Setting up the bin system...")),await k.createBinDirectoryStructure();const t=k.getBinDirectory();console.log(e.green(`Bin directory: ${t}`));if(k.checkIfInPath(t))console.log(e.green("Bin directory is already in PATH."));else{console.log(e.yellow("Bin directory is not in PATH."));let a=o.yes;if(o.yes)console.log(e.yellow("Auto-confirming to add bin directory to PATH due to --yes flag"));else{a=(await i({type:"confirm",name:"confirmAddToPath",message:`Would you like to add ${t} to your PATH?`,initial:!0})).confirmAddToPath}if(a){let a=k.detectUserShell();if("unknown"===a)if(o.yes)a="win32"===process.platform?"powershell":"bash",console.log(e.yellow(`Auto-selecting ${a} shell due to --yes flag`));else{const{selectedShell:e}=await i({type:"select",name:"selectedShell",message:"Select your shell:",choices:[{name:"bash",message:"Bash"},{name:"zsh",message:"Zsh"},{name:"fish",message:"Fish"},{name:"powershell",message:"PowerShell"},{name:"powershell-core",message:"PowerShell Core"},{name:"cmd",message:"Windows Command Prompt"},{name:"ksh",message:"Korn Shell (ksh)"},{name:"csh",message:"C Shell (csh/tcsh)"}]});a=e}else if(o.yes)console.log(e.yellow(`Auto-confirming detected shell: ${a} due to --yes flag`));else{const{confirmShell:e}=await i({type:"confirm",name:"confirmShell",message:`Detected shell: ${a}. Is this correct?`,initial:!0});if(!e){const{selectedShell:e}=await i({type:"select",name:"selectedShell",message:"Select your shell:",choices:[{name:"bash",message:"Bash"},{name:"zsh",message:"Zsh"},{name:"fish",message:"Fish"},{name:"powershell",message:"PowerShell"},{name:"powershell-core",message:"PowerShell Core"},{name:"cmd",message:"Windows Command Prompt"},{name:"ksh",message:"Korn Shell (ksh)"},{name:"csh",message:"C Shell (csh/tcsh)"}]});a=e}}const r=k.getAllShellConfigPaths(a);let c;if(r.length>1){const t=r.filter((e=>n.existsSync(e.path)));if(t.length>0)if(o.yes)c=t[0].path,console.log(e.yellow(`Auto-selecting config file: ${c} due to --yes flag`));else{const{selectedConfigPath:e}=await i({type:"select",name:"selectedConfigPath",message:"Select the configuration file to modify:",choices:t.map((e=>({name:e.path,message:`${e.name} (${e.path})`})))});c=e}else if(o.yes)c=r[0].path,console.log(e.yellow(`Auto-selecting config file to create: ${c} due to --yes flag`));else{const{selectedConfigPath:e}=await i({type:"select",name:"selectedConfigPath",message:"Select the configuration file to create:",choices:r.map((e=>({name:e.path,message:`${e.name} (${e.path})`})))});c=e}}else if(1===r.length)c=r[0].path;else if(o.yes)c=s.join(l.homedir(),"win32"===process.platform?"_profile":".bashrc"),console.log(e.yellow(`Auto-selecting default config file: ${c} due to --yes flag`));else{const{enteredConfigPath:e}=await i({type:"input",name:"enteredConfigPath",message:"Enter the path to your shell configuration file:",initial:s.join(l.homedir(),".bashrc")});c=e}await k.addBinToPath(a,c,t)?(console.log(e.green(`Added bin directory to PATH in ${c}`)),console.log(e.yellow("Please restart your terminal or run the following command:")),console.log(e.green(`source ${c}`))):(console.log(e.red(`Failed to add bin directory to PATH in ${c}`)),console.log(e.yellow("You can add it manually by adding the following line to your shell configuration:")),console.log(e.green(k.getExportPathCommand(a,t))))}else console.log(e.yellow("You can add it manually by adding the following line to your shell configuration:")),console.log(e.green(`export PATH="${t}:$PATH"`)),console.log(e.yellow("Or run:")),console.log(e.green("fbin path"))}console.log(e.green("Bin system setup completed successfully."))}catch(o){console.error(e.red(`Failed to set up bin system: ${o.message}`)),process.exit(1)}}};var x={command:"path",describe:"Add bin directory to PATH",builder:{yes:{describe:"Automatically answer yes to all prompts",type:"boolean",default:!1,alias:"y"}},handler:async o=>{try{await P(o);const t=k.getBinDirectory();console.log(e.blue(`Adding ${t} to PATH...`)),k.createBinDirectoryStructure()||(console.log(e.yellow("Creating bin directory structure...")),await k.createBinDirectoryStructure());if(k.checkIfInPath(t))return void console.log(e.green("Bin directory is already in PATH."));let a=k.detectUserShell();if("unknown"===a)if(o.yes)a="win32"===process.platform?"powershell":"bash",console.log(e.yellow(`Auto-selecting ${a} shell due to --yes flag`));else{const{selectedShell:e}=await i({type:"select",name:"selectedShell",message:"Select your shell:",choices:[{name:"bash",message:"Bash"},{name:"zsh",message:"Zsh"},{name:"fish",message:"Fish"},{name:"powershell",message:"PowerShell"},{name:"powershell-core",message:"PowerShell Core"},{name:"cmd",message:"Windows Command Prompt"},{name:"ksh",message:"Korn Shell (ksh)"},{name:"csh",message:"C Shell (csh/tcsh)"}]});a=e}else if(o.yes)console.log(e.yellow(`Auto-confirming detected shell: ${a} due to --yes flag`));else{const{confirmShell:e}=await i({type:"confirm",name:"confirmShell",message:`Detected shell: ${a}. Is this correct?`,initial:!0});if(!e){const{selectedShell:e}=await i({type:"select",name:"selectedShell",message:"Select your shell:",choices:[{name:"bash",message:"Bash"},{name:"zsh",message:"Zsh"},{name:"fish",message:"Fish"},{name:"powershell",message:"PowerShell"},{name:"powershell-core",message:"PowerShell Core"},{name:"cmd",message:"Windows Command Prompt"},{name:"ksh",message:"Korn Shell (ksh)"},{name:"csh",message:"C Shell (csh/tcsh)"}]});a=e}}const r=k.getAllShellConfigPaths(a);let c;if(r.length>1){const t=r.filter((e=>n.existsSync(e.path)));if(t.length>0)if(o.yes)c=t[0].path,console.log(e.yellow(`Auto-selecting config file: ${c} due to --yes flag`));else{const{selectedConfigPath:e}=await i({type:"select",name:"selectedConfigPath",message:"Select the configuration file to modify:",choices:t.map((e=>({name:e.path,message:`${e.name} (${e.path})`})))});c=e}else if(o.yes)c=r[0].path,console.log(e.yellow(`Auto-selecting config file to create: ${c} due to --yes flag`));else{const{selectedConfigPath:e}=await i({type:"select",name:"selectedConfigPath",message:"Select the configuration file to create:",choices:r.map((e=>({name:e.path,message:`${e.name} (${e.path})`})))});c=e}}else if(1===r.length)c=r[0].path;else if(o.yes)c=s.join(l.homedir(),"win32"===process.platform?"_profile":".bashrc"),console.log(e.yellow(`Auto-selecting default config file: ${c} due to --yes flag`));else{const{enteredConfigPath:e}=await i({type:"input",name:"enteredConfigPath",message:"Enter the path to your shell configuration file:",initial:s.join(l.homedir(),".bashrc")});c=e}await k.addBinToPath(a,c,t)?(console.log(e.green(`Added bin directory to PATH in ${c}`)),console.log(e.yellow("Please restart your terminal or run the following command:")),console.log(e.green(`source ${c}`))):(console.log(e.red(`Failed to add bin directory to PATH in ${c}`)),console.log(e.yellow("You can add it manually by adding the following line to your shell configuration:")),console.log(e.green(k.getExportPathCommand(a,t))))}catch(o){console.error(e.red(`Failed to add bin directory to PATH: ${o.message}`)),process.exit(1)}}};var A={command:"compile [source] [options]",describe:"Compile a CLI project to a binary",builder:{source:{describe:"Source file to compile",type:"string",default:"./dist/cli/esm/index.js"},output:{describe:"Output file name",type:"string",alias:"o"},name:{describe:"Binary name",type:"string",alias:"n"},force:{describe:"Force overwrite if binary already exists",type:"boolean",default:!1,alias:"f"},yes:{describe:"Automatically answer yes to all prompts",type:"boolean",default:!1,alias:"y"},target:{describe:"Target platform (auto, linux, macos, windows)",type:"string",choices:["auto","linux","macos","windows"],default:"auto"},minify:{describe:"Minify the output binary",type:"boolean",default:!0},external:{describe:"External packages to exclude from the bundle (comma-separated)",type:"string"}},handler:async o=>{try{await P(o);const t=process.cwd(),l=s.basename(t),a=o.name||l;let r;if(o.output)r=o.output;else{const e=s.join(t,".bin");n.existsSync(e)||n.mkdirSync(e,{recursive:!0}),r=s.join(e,a)}const c=s.resolve(process.cwd(),o.source);if(n.existsSync(c)||(console.error(e.red(`Source file not found: ${c}`)),console.error(e.yellow("Make sure to build your project first.")),process.exit(1)),n.existsSync(r)&&!o.force&&!o.yes){const{confirmOverwrite:o}=await i({type:"confirm",name:"confirmOverwrite",message:`Binary already exists at ${r}. Overwrite?`,initial:!1});if(!o)return void console.log(e.yellow("Compilation cancelled."))}const d=process.platform;console.log(e.blue(`Detected platform: ${d}`)),"win32"!==d||r.endsWith(".exe")||(r=`${r}.exe`,console.log(e.blue(`Adjusted output path for Windows: ${r}`))),console.log(e.blue(`Compiling ${c} to ${r}...`));const{spawn:m}=await import("child_process");try{const e=m("bun",["--version"],{stdio:"pipe"});await new Promise(((o,t)=>{e.on("close",(e=>{0===e?o():t(new Error("Bun is not available. Please install Bun first."))})),e.on("error",(e=>{t(new Error(`Bun is not available: ${e.message}`))}))}))}catch(o){console.error(e.red(`Bun is not available: ${o.message}`)),console.error(e.yellow("Please install Bun first: https://bun.sh/")),process.exit(1)}const u=["build",c,"--compile",`--outfile=${r}`];if(o.target&&"auto"!==o.target&&u.push(`--target=${o.target}`),!1===o.minify&&u.push("--no-minify"),o.external){o.external.split(",").map((e=>e.trim())).forEach((e=>{u.push(`--external:${e}`)}))}console.log(e.blue(`Running: bun ${u.join(" ")}`));const g=m("bun",u,{stdio:"inherit"});await new Promise(((e,o)=>{g.on("close",(t=>{0===t?e():o(new Error(`Compilation failed with code ${t}`))})),g.on("error",(e=>{o(e)}))})),"win32"!==d&&n.chmodSync(r,493),console.log(e.green(`Binary compiled successfully: ${r}`)),"win32"===d?console.log(e.yellow("Note: On Windows, you may need to run the binary from a command prompt or PowerShell.")):"darwin"===d&&console.log(e.yellow("Note: On macOS, you may need to allow the binary to run in System Preferences > Security & Privacy."))}catch(o){console.error(e.red(`Failed to compile binary: ${o.message}`)),process.exit(1)}}};var B={command:"install [source] [options]",describe:"Install a binary to the bin directory",builder:{source:{describe:"Source binary to install",type:"string",demandOption:!0},name:{describe:"Name to use for the installed binary",type:"string",alias:"n"},force:{describe:"Force overwrite if binary already exists",type:"boolean",default:!1,alias:"f"},yes:{describe:"Automatically answer yes to all prompts",type:"boolean",default:!1,alias:"y"}},handler:async o=>{try{await P(o);const t=s.resolve(process.cwd(),o.source);n.existsSync(t)||(console.error(e.red(`Source file not found: ${t}`)),process.exit(1)),await k.createBinDirectoryStructure();const l=k.getBinDirectory();let a;a=o.name?o.name:s.basename(t),"win32"!==process.platform||a.endsWith(".exe")||(a=`${a}.exe`);const r=s.join(l,a);if(n.existsSync(r)&&!o.force&&!o.yes){const{confirmOverwrite:o}=await i({type:"confirm",name:"confirmOverwrite",message:`Binary already exists at ${r}. Overwrite?`,initial:!1});if(!o)return void console.log(e.yellow("Installation cancelled."))}console.log(e.blue(`Installing ${t} to ${r}...`)),n.copyFileSync(t,r),"win32"!==process.platform&&n.chmodSync(r,493);const c=k.getMetadataFilePath();let d={binaries:{},lastUpdated:(new Date).toISOString()};if(n.existsSync(c))try{d=JSON.parse(n.readFileSync(c,"utf8"))}catch(o){console.warn(e.yellow(`Failed to parse metadata file: ${o.message}`)),console.warn(e.yellow("Creating new metadata file."))}let m="0.0.0";try{const{execSync:o}=require("child_process"),t=o(`"${r}" --version`,{timeout:5e3,stdio:["ignore","pipe","ignore"]}).toString().trim(),s=t.match(/v?(\d+\.\d+\.\d+)/);s?(m=s[1],console.log(e.blue(`Detected binary version: ${m}`))):(console.log(e.yellow(`Could not parse version from output: ${t}`)),console.log(e.yellow(`Using default version: ${m}`)))}catch(o){console.log(e.yellow(`Could not detect binary version, using default: ${m}`))}d.binaries[a]={path:r,source:t,created:(new Date).toISOString(),platform:process.platform,version:m,project:s.basename(process.cwd())},d.lastUpdated=(new Date).toISOString(),n.writeFileSync(c,JSON.stringify(d,null,2)),console.log(e.green(`Binary installed successfully: ${r}`));k.checkIfInPath(l)?console.log(e.green(`You can now run '${a}' from anywhere.`)):console.log(e.yellow("Bin directory is not in PATH. Run 'fbin path' to add it."))}catch(o){console.error(e.red(`Failed to install binary: ${o.message}`)),process.exit(1)}}};var F={promptForSelection:async function(o){const{items:t,message:s,nameField:n="name",valueField:l="name",initialValue:a=null,allowAbort:r=!0}=o;if(!t||0===t.length)return console.log(e.yellow("No items available for selection.")),null;if(1===t.length&&!r){const o=t[0],s="string"==typeof o?o:o[l];return console.log(e.blue(`Only one option available: ${"string"==typeof o?o:o[n]}`)),s}let c=t.map((e=>"string"==typeof e?{name:e,value:e,message:e}:{name:e[l],value:e[l],message:e[n]||e[l]}));r&&c.push({name:"cancel",value:null,message:e.yellow("Cancel")});let d=null;if(a){const e=c.findIndex((e=>e.name===a));-1!==e&&(d=e)}const m="selectedItem",{[m]:u}=await i({type:"select",name:m,message:s,choices:c,initial:d});return"cancel"===u?null:u},promptForMultipleSelection:async function(o){const{items:t,message:s,nameField:n="name",valueField:l="name",initialValues:a=[],allowAbort:r=!0}=o;if(!t||0===t.length)return console.log(e.yellow("No items available for selection.")),null;let c=t.map((e=>"string"==typeof e?{name:e,value:e,message:e}:{name:e[l],value:e[l],message:e[n]||e[l]})),d=[];a&&a.length>0&&(d=c.map(((e,o)=>a.includes(e.name)?o:-1)).filter((e=>-1!==e)));const m="selectedItems",u=await i({type:"multiselect",name:m,message:s,choices:c,initial:d,hint:"(Use space to select, enter to confirm)",validate:e=>!(0===e.length&&!r)||"Please select at least one item"});return r&&0===u[m].length?null:u[m]}};var j={command:"uninstall [name] [options]",describe:"Uninstall a binary from the bin directory",builder:{name:{describe:"Name of the binary to uninstall",type:"string",demandOption:!1},force:{describe:"Skip confirmation prompt",type:"boolean",default:!1,alias:"f"},yes:{describe:"Automatically answer yes to all prompts",type:"boolean",default:!1,alias:"y"}},handler:async o=>{try{await P(o);const t=k.getBinDirectory(),s=k.getMetadataFilePath();let l;n.existsSync(t)||(console.error(e.red(`Bin directory not found: ${t}`)),console.error(e.yellow("Run fbin setup first.")),process.exit(1)),n.existsSync(s)||(console.error(e.red(`Metadata file not found: ${s}`)),console.error(e.yellow("Run fbin setup first.")),process.exit(1));try{l=JSON.parse(n.readFileSync(s,"utf8"))}catch(o){console.error(e.red(`Failed to parse metadata file: ${o.message}`)),process.exit(1)}if(!o.name&&!o.yes){const t=Object.keys(l.binaries);if(0===t.length)return void console.log(e.yellow("No binaries installed."));const s=await F.promptForSelection({items:t,message:"Select a binary to uninstall:",allowAbort:!0});if(null===s)return void console.log(e.yellow("Uninstallation cancelled."));o.name=s}const a=o.name;a||(console.error(e.red("Binary name is required.")),console.error(e.yellow("Use --name to specify a binary or run without --yes to select interactively.")),process.exit(1)),l.binaries[a]||(console.error(e.red(`Binary not found in metadata: ${a}`)),console.log(e.yellow("Use fbin list to see installed binaries.")),process.exit(1));const r=l.binaries[a].path;if(n.existsSync(r)||(console.warn(e.yellow(`Binary file not found: ${r}`)),console.warn(e.yellow("Metadata will be updated anyway."))),!o.force&&!o.yes){const{confirmUninstall:o}=await i({type:"confirm",name:"confirmUninstall",message:`Are you sure you want to uninstall ${a}?`,initial:!1});if(!o)return void console.log(e.yellow("Uninstallation cancelled."))}if(n.existsSync(r))try{n.unlinkSync(r),console.log(e.green(`Binary file removed: ${r}`))}catch(o){console.error(e.red(`Failed to remove binary file: ${o.message}`))}delete l.binaries[a],l.lastUpdated=(new Date).toISOString(),n.writeFileSync(s,JSON.stringify(l,null,2)),console.log(e.green(`Binary uninstalled successfully: ${a}`))}catch(o){console.error(e.red(`Failed to uninstall binary: ${o.message}`)),process.exit(1)}}};function C(o,t={}){const s={chars:{top:"─","top-mid":"─","top-left":" ","top-right":" ",bottom:"─","bottom-mid":"─","bottom-left":" ","bottom-right":" ",left:" ","left-mid":" ",mid:"─","mid-mid":"─",right:" ","right-mid":" ",middle:" "},style:{head:[],border:[],compact:!0},wordWrap:!0,...t,head:o.map((o=>e.bold(o)))};return new r(s)}var T={createTable:C,createTableWithData:function(e,o,t={}){const s=C(e,t);return Array.isArray(o)&&o.forEach((e=>{s.push(e)})),s.toString()},getStatusColor:function(o){switch(o){case"running":return e.green;case"stopped":return e.yellow;case"failed":return e.red;case"registered":return e.blue;default:return e.gray}}};var D={command:"list [options]",describe:"List installed binaries",builder:{json:{describe:"Output in JSON format",type:"boolean",default:!1,alias:"j"},filter:{describe:"Filter binaries by name",type:"string",alias:"f"}},handler:async o=>{try{await P(o);const t=k.getBinDirectory(),s=k.getMetadataFilePath();let l;n.existsSync(t)||(console.error(e.red(`Bin directory not found: ${t}`)),console.error(e.yellow("Run fbin setup first.")),process.exit(1)),n.existsSync(s)||(console.error(e.red(`Metadata file not found: ${s}`)),console.error(e.yellow("Run fbin setup first.")),process.exit(1));try{l=JSON.parse(n.readFileSync(s,"utf8"))}catch(o){console.error(e.red(`Failed to parse metadata file: ${o.message}`)),process.exit(1)}let i=l.binaries;if(o.filter){const e=o.filter.toLowerCase();i=Object.entries(i).filter((([o])=>o.toLowerCase().includes(e))).reduce(((e,[o,t])=>(e[o]=t,e)),{})}if(o.json)return void console.log(JSON.stringify(i,null,2));const a=Object.keys(i).length;if(0===a)return void console.log(e.yellow("No binaries installed."));console.log(e.blue(`Found ${a} installed binaries:`)),console.log();const r=["NAME","VERSION","PLATFORM","CREATED"],c=T.createTable(r,{chars:{mid:"","mid-mid":"","left-mid":"","right-mid":""}});Object.entries(i).forEach((([o,t])=>{const s=new Date(t.created).toLocaleString();c.push([e.white(o),t.version||"N/A",t.platform||"N/A",s])})),console.log(c.toString()),console.log(),console.log(e.blue(`Bin directory: ${t}`));k.checkIfInPath(t)||console.log(e.yellow("Bin directory is not in PATH. Run 'fbin path' to add it."))}catch(o){console.error(e.red(`Failed to list binaries: ${o.message}`)),process.exit(1)}}};var O={command:"backup [options]",describe:"Backup shell configs and binaries",builder:{config:{describe:"Backup shell configuration files",type:"boolean",default:!1,alias:"c"},binaries:{describe:"Backup installed binaries",type:"boolean",default:!1,alias:"b"},all:{describe:"Backup everything (configs + binaries)",type:"boolean",default:!1,alias:"a"},message:{describe:"Backup description message",type:"string",alias:"m"}},handler:async o=>{try{await P(o);const t=o.all||!o.config&&!o.binaries,l=o.config||t,i=o.binaries||t;console.log(e.blue("Creating backup..."));const a=k.createBackupDirectory(),r=[];if(l){console.log(e.blue("Backing up shell configurations..."));const o=s.join(a,"configs");n.mkdirSync(o,{recursive:!0});const t=k.detectUserShell(),l=k.getAllShellConfigPaths(t);let i=0;for(const t of l)if(n.existsSync(t.path)){k.backupFile(t.path,o,t.name)&&(r.push(t.path),i++,console.log(e.green(` ✓ ${t.name}`)))}0===i?console.log(e.yellow(" No configuration files found to backup")):console.log(e.green(` Backed up ${i} configuration file(s)`))}if(i){console.log(e.blue("Backing up binaries..."));const o=s.join(a,"binaries");n.mkdirSync(o,{recursive:!0});const t=k.getBinDirectory(),l=k.getMetadataFilePath();if(n.existsSync(l)&&(k.backupFile(l,o,"metadata.json"),r.push(l)),n.existsSync(t)){const l=n.readdirSync(t);let i=0;for(const a of l){const l=s.join(t,a);if(n.statSync(l).isFile()){k.backupFile(l,o,a)&&(r.push(l),i++,console.log(e.green(` ✓ ${a}`)))}}0===i?console.log(e.yellow(" No binaries found to backup")):console.log(e.green(` Backed up ${i} binary(ies)`))}else console.log(e.yellow(" Bin directory not found"))}k.createBackupMetadata(a,{type:"manual",command:"fbin backup",message:o.message||"Manual backup",files:r,config:l,binaries:i}),k.updateLatestSymlink(a),console.log(),console.log(e.green("✓ Backup created successfully!")),console.log(e.blue(` Location: ${a}`)),console.log(e.blue(` Files backed up: ${r.length}`)),o.message&&console.log(e.blue(` Message: ${o.message}`))}catch(o){console.error(e.red(`Failed to create backup: ${o.message}`)),process.exit(1)}}};var M={command:"restore [options]",describe:"Restore from backup",builder:{config:{describe:"Restore shell configuration files",type:"boolean",default:!1,alias:"c"},binaries:{describe:"Restore installed binaries",type:"boolean",default:!1,alias:"b"},all:{describe:"Restore everything (configs + binaries)",type:"boolean",default:!1,alias:"a"},list:{describe:"List available backups",type:"boolean",default:!1,alias:"l"},timestamp:{describe:"Backup timestamp to restore (defaults to latest)",type:"string",alias:"t"},yes:{describe:"Automatically answer yes to all prompts",type:"boolean",default:!1,alias:"y"}},handler:async o=>{try{await P(o);if(o.list){const o=k.listBackups();if(0===o.length)return void console.log(e.yellow("No backups found."));console.log(e.blue(`Found ${o.length} backup(s):\n`));const t=["TIMESTAMP","TYPE","MESSAGE","FILES"],s=T.createTable(t,{chars:{mid:"","mid-mid":"","left-mid":"","right-mid":""}});for(const t of o){const o=t.timestamp||"unknown",n=t.type||"manual",l=t.message||"",i=t.files?t.files.length:0;s.push([e.white(o),n,l.substring(0,40)+(l.length>40?"...":""),i.toString()])}return console.log(s.toString()),console.log(),void console.log(e.blue(`Backup directory: ${k.getBackupDirectory()}`))}const t=k.listBackups();if(0===t.length)return console.log(e.yellow("No backups found.")),void console.log(e.blue("Create a backup first with: fbin backup"));let l;if(o.timestamp)l=t.find((e=>e.timestamp===o.timestamp)),l||(console.error(e.red(`Backup not found: ${o.timestamp}`)),console.log(e.yellow("Use --list to see available backups")),process.exit(1));else if(o.yes)l=t[0],console.log(e.yellow(`Auto-selecting latest backup: ${l.timestamp}`));else{const o=t.map((e=>({name:e.timestamp,message:`${e.timestamp} - ${e.message||"No message"} (${e.files?.length||0} files)`}))),s=await F.promptForSelection({items:o.map((e=>e.name)),message:"Select a backup to restore:",allowAbort:!0});if(null===s)return void console.log(e.yellow("Restore cancelled."));l=t.find((e=>e.timestamp===s))}console.log(e.blue(`Restoring from backup: ${l.timestamp}`));const a=o.all||!o.config&&!o.binaries,r=o.config||a,c=o.binaries||a;if(!o.yes){const{confirmRestore:o}=await i({type:"confirm",name:"confirmRestore",message:"This will overwrite current files. Continue?",initial:!1});if(!o)return void console.log(e.yellow("Restore cancelled."))}let d=0;if(r){const o=s.join(l.path,"configs");if(n.existsSync(o)){console.log(e.blue("Restoring shell configurations..."));const t=n.readdirSync(o);for(const l of t){const t=s.join(o,l),i=k.detectUserShell(),a=k.getAllShellConfigPaths(i).find((e=>e.name===l));if(a){const o=a.path,i=s.dirname(o);n.existsSync(i)||n.mkdirSync(i,{recursive:!0}),n.copyFileSync(t,o),console.log(e.green(` ✓ ${l}`)),d++}}}}if(c){const o=s.join(l.path,"binaries");if(n.existsSync(o)){console.log(e.blue("Restoring binaries..."));const t=k.getBinDirectory();n.existsSync(t)||n.mkdirSync(t,{recursive:!0});const l=n.readdirSync(o);for(const i of l){const l=s.join(o,i),a=s.join(t,i);if("metadata.json"!==i)n.copyFileSync(l,a),"win32"!==process.platform&&n.chmodSync(a,493),console.log(e.green(` ✓ ${i}`)),d++;else{const o=k.getMetadataFilePath(),t=s.dirname(o);n.existsSync(t)||n.mkdirSync(t,{recursive:!0}),n.copyFileSync(l,o),console.log(e.green(" ✓ metadata.json")),d++}}}}console.log(),console.log(e.green("✓ Restore completed successfully!")),console.log(e.blue(` Files restored: ${d}`))}catch(o){console.error(e.red(`Failed to restore backup: ${o.message}`)),process.exit(1)}}};var N={command:"cleanup [options]",describe:"Clean up old backups",builder:{keep:{describe:"Number of recent backups to keep",type:"number",default:10,alias:"k"},older:{describe:"Remove backups older than N days",type:"number",alias:"o"},all:{describe:"Remove all backups",type:"boolean",default:!1,alias:"a"},yes:{describe:"Automatically answer yes to all prompts",type:"boolean",default:!1,alias:"y"},"dry-run":{describe:"Show what would be deleted without actually deleting",type:"boolean",default:!1,alias:"d"}},handler:async o=>{try{await P(o);const t=k.listBackups();if(0===t.length)return void console.log(e.yellow("No backups found."));console.log(e.blue(`Found ${t.length} backup(s)`));let l=[];if(o.all)l=t;else if(o.older){const s=new Date;s.setDate(s.getDate()-o.older),l=t.filter((e=>new Date(e.created)<s)),console.log(e.blue(`Removing backups older than ${o.older} days (before ${s.toLocaleDateString()})`))}else{if(!(t.length>o.keep))return void console.log(e.green(`Only ${t.length} backup(s) found, keeping all (limit: ${o.keep})`));l=t.slice(o.keep),console.log(e.blue(`Keeping ${o.keep} most recent backup(s), removing ${l.length} old backup(s)`))}if(0===l.length)return void console.log(e.green("No backups to delete."));console.log(),console.log(e.yellow(`Backups to be deleted (${l.length}):`)),console.log();const a=["TIMESTAMP","TYPE","MESSAGE","FILES","SIZE"],r=T.createTable(a,{chars:{mid:"","mid-mid":"","left-mid":"","right-mid":""}});let c=0;for(const o of l){const t=o.timestamp||"unknown",l=o.type||"manual",i=o.message||"",a=o.files?o.files.length:0;let d=0;try{const e=o=>{let t=0;const l=n.readdirSync(o);for(const i of l){const l=s.join(o,i),a=n.statSync(l);a.isDirectory()?t+=e(l):t+=a.size}return t};d=e(o.path),c+=d}catch(e){}const m=d>0?`${(d/1024/1024).toFixed(2)} MB`:"N/A";r.push([e.white(t),l,i.substring(0,30)+(i.length>30?"...":""),a.toString(),m])}if(console.log(r.toString()),console.log(),console.log(e.blue(`Total size to free: ${(c/1024/1024).toFixed(2)} MB`)),o["dry-run"])return console.log(),console.log(e.yellow("DRY RUN: No backups were deleted.")),void console.log(e.blue("Run without --dry-run to actually delete these backups."));if(!o.yes){console.log();const{confirmDelete:o}=await i({type:"confirm",name:"confirmDelete",message:`Delete ${l.length} backup(s)?`,initial:!1});if(!o)return void console.log(e.yellow("Cleanup cancelled."))}console.log(),console.log(e.blue("Deleting backups..."));let d=0,m=0;for(const o of l)try{n.rmSync(o.path,{recursive:!0,force:!0}),console.log(e.green(` ✓ ${o.timestamp}`)),d++}catch(t){console.log(e.red(` ✗ ${o.timestamp}: ${t.message}`)),m++}console.log(),console.log(e.green("✓ Cleanup completed!")),console.log(e.blue(` Deleted: ${d}`)),m>0&&console.log(e.yellow(` Failed: ${m}`)),console.log(e.blue(` Space freed: ${(c/1024/1024).toFixed(2)} MB`));const u=k.listBackups();console.log(e.blue(` Remaining backups: ${u.length}`))}catch(o){console.error(e.red(`Failed to cleanup backups: ${o.message}`)),process.exit(1)}}};c(d);let I=!1;process.on("uncaughtException",(e=>{I||(I=!0,setTimeout((()=>process.exit(1)),500))})),process.on("unhandledRejection",(e=>{I||(I=!0,setTimeout((()=>process.exit(1)),500))})),async function(){try{o(t(process.argv)).usage("Usage: $0 <command> [options]").command(v).command(x).command(A).command(B).command(j).command(D).command(O).command(M).command(N).demandCommand(1,"You need to specify a command").help().version().argv}catch(o){console.error(e.red(`Fatal error: ${o.message}`)),process.exit(1)}}().catch((o=>{console.error(e.red(`Fatal error: ${o.message}`)),process.exit(1)}));