@stacksjs/buddy 0.75.623 → 0.75.625

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/cli.js CHANGED
@@ -1,7 +1,7 @@
1
- #!/usr/bin/env bun
1
+ #!/usr/bin/env -S bun --config=/dev/null --no-install
2
2
  import{writeSync}from"node:fs";import process from"node:process";import{registerGlobalOptions}from"./global-options";import{shouldSkipAppKeyCheck}from"./project-setup";import{resultFailed}from"./result";import{versionLine}from"./version-info";if(import.meta.main)await runCli();async function runCli(){const typedArgs=process.argv.slice(2);const isVersionOnly=typedArgs.length===1&&["--version","-V","version"].includes(typedArgs[0]);if(isVersionOnly){writeSync(process.stdout.fd,`${versionLine} ${process.platform}-${process.arch} bun-v${Bun.version}
3
- `);process.exit(0)}const[{HANDED_ROOT_ENV,launch},{getCommandNames}]=await Promise.all([import("./launcher"),import("./lazy-commands")]);launch({args:typedArgs,cwd:process.cwd(),main:Bun.main,execArgv:process.execArgv,handedRoot:process.env[HANDED_ROOT_ENV],builtInCommands:new Set(getCommandNames())});const args=process.argv.slice(2);const requestedCommand=args[0]||"help";const{isNativeProject,runNativeProjectCommand}=await import("./native-project");if(isNativeProject(process.cwd())){try{if(await runNativeProjectCommand(process.cwd(),args))process.exit(0)}catch(error){console.error(`[buddy] ${error instanceof Error?error.message:String(error)}`);process.exit(1)}}const[{cli,log},{path:p}]=await Promise.all([import("@stacksjs/cli"),import("@stacksjs/path")]);try{const{isSupportedBunVersion,minimumBunVersion}=await import("@stacksjs/utils");const currentBunVersion=typeof Bun!=="undefined"?Bun.version:process.versions.bun;if(currentBunVersion&&!isSupportedBunVersion(currentBunVersion)){console.error(`[buddy] Bun v${minimumBunVersion} or later is required (current: v${currentBunVersion}). Run: bun upgrade`);process.exit(1)}}catch{}const isHelpFlag=args.includes("--help")||args.includes("-h");const isHelpMode=requestedCommand==="help"||isHelpFlag&&args.length<=2;const skipAppKeyCheck=shouldSkipAppKeyCheck(requestedCommand,{isHelpFlag,isHelpMode});const needsFullSetup=!isVersionOnly;if(!process.env.LOG_LEVEL){if(args.includes("--quiet")||args.includes("-q"))process.env.LOG_LEVEL="warn";else if(args.includes("--verbose")||args.includes("-v"))process.env.LOG_LEVEL="debug"}if(needsFullSetup){const reportFatal=(label,error)=>{log.debug(`Buddy ${label}`);try{process.stderr.write(`
3
+ `);process.exit(0)}const[{HANDED_ROOT_ENV,launch},{getCommandNames}]=await Promise.all([import("./launcher"),import("./lazy-commands")]);const{projectInstalled}=launch({args:typedArgs,cwd:process.cwd(),main:Bun.main,execArgv:process.execArgv,handedRoot:process.env[HANDED_ROOT_ENV],builtInCommands:new Set(getCommandNames())});const args=process.argv.slice(2);const requestedCommand=args[0]||"help";const{isNativeProject,runNativeProjectCommand}=await import("./native-project");if(isNativeProject(process.cwd())){try{if(await runNativeProjectCommand(process.cwd(),args))process.exit(0)}catch(error){console.error(`[buddy] ${error instanceof Error?error.message:String(error)}`);process.exit(1)}}const[{cli,log},{path:p}]=await Promise.all([import("@stacksjs/cli"),import("@stacksjs/path")]);try{const{isSupportedBunVersion,minimumBunVersion}=await import("@stacksjs/utils");const currentBunVersion=typeof Bun!=="undefined"?Bun.version:process.versions.bun;if(currentBunVersion&&!isSupportedBunVersion(currentBunVersion)){console.error(`[buddy] Bun v${minimumBunVersion} or later is required (current: v${currentBunVersion}). Run: bun upgrade`);process.exit(1)}}catch{}const isHelpFlag=args.includes("--help")||args.includes("-h");const isHelpMode=requestedCommand==="help"||isHelpFlag&&args.length<=2;const skipAppKeyCheck=shouldSkipAppKeyCheck(requestedCommand,{isHelpFlag,isHelpMode});const needsFullSetup=!isVersionOnly;if(!process.env.LOG_LEVEL){if(args.includes("--quiet")||args.includes("-q"))process.env.LOG_LEVEL="warn";else if(args.includes("--verbose")||args.includes("-v"))process.env.LOG_LEVEL="debug"}if(needsFullSetup){const reportFatal=(label,error)=>{log.debug(`Buddy ${label}`);try{process.stderr.write(`
4
4
  [buddy] ${label}: ${error?.stack??String(error)}
5
- `)}catch{}log.error(error);return process.exit(1)};process.on("uncaughtException",(error)=>reportFatal("uncaughtException",error));process.on("unhandledRejection",(error)=>reportFatal("unhandledRejection",error))}async function main(){const buddy=cli("buddy");registerGlobalOptions(buddy,{version:requestedCommand!=="upgrade"&&requestedCommand!=="update"});const configPath="./buddy.config.js";try{await Bun.file(configPath).text();const{applyBuddyConfig}=await import("./config.js");await applyBuddyConfig(buddy)}catch{}if(needsFullSetup){p.ensureRuntimeDirectories();const{loadCommands,getCommandsToLoad}=await import("./lazy-commands.js");if(!skipAppKeyCheck){const{runAction}=await import("@stacksjs/actions");const{Action}=await import("@stacksjs/enums");const{ensureProjectIsInitialized}=await import("@stacksjs/utils");const isAppKeySet=await ensureProjectIsInitialized();if(!isAppKeySet){log.info("Your `APP_KEY` is not yet set");log.info("Generating application key...");const result=await runAction(Action.KeyGenerate);if(resultFailed(result)){await log.error("Failed to set random application key.",result.error);process.exit(1)}}}const commandsToLoad=getCommandsToLoad(args);await loadCommands(commandsToLoad,buddy);await dynamicImports(buddy)}else{const{loadCommand}=await import("./lazy-commands.js");await loadCommand("version",buddy)}buddy.help();if(args.length===0&&process.stdin.isTTY&&!buddy.isNoInteraction){await showInteractiveMenu(buddy)}else{await parseOrExit(buddy)}}async function showInteractiveMenu(buddy){const{bold,green,intro}=await import("@stacksjs/cli");const{select}=await import("@stacksjs/cli");await intro("buddy");console.log(bold(green("What would you like to do?")));console.log("");const choice=await select({message:"Select a command:",choices:[{value:"dev",label:"Start development server"},{value:"build",label:"Build for production"},{value:"test",label:"Run tests"},{value:"list",label:"List all commands"},{value:"doctor",label:"Run health checks"},{value:"about",label:"Show system information"},{value:"help",label:"Show help"},{value:"exit",label:"Exit"}],initial:0});console.log("");if(choice==="exit"){process.exit(0)}else if(choice==="help"){buddy.outputHelp()}else{process.argv=["bun","buddy",choice];await parseOrExit(buddy)}}async function parseOrExit(buddy){try{await buddy.parse()}catch(error){const isUsageError=error?.name==="ClappError"||error?.isUsageError===true;if(!isUsageError)throw error;process.stderr.write(`${error.message}
5
+ `)}catch{}log.error(error);return process.exit(1)};process.on("uncaughtException",(error)=>reportFatal("uncaughtException",error));process.on("unhandledRejection",(error)=>reportFatal("unhandledRejection",error))}async function main(){const buddy=cli("buddy");registerGlobalOptions(buddy,{version:requestedCommand!=="upgrade"&&requestedCommand!=="update"});const configPath="./buddy.config.js";try{await Bun.file(configPath).text();const{applyBuddyConfig}=await import("./config.js");await applyBuddyConfig(buddy)}catch{}if(needsFullSetup){p.ensureRuntimeDirectories();const{loadCommands,getCommandsToLoad}=await import("./lazy-commands.js");if(!skipAppKeyCheck){const{runAction}=await import("@stacksjs/actions");const{Action}=await import("@stacksjs/enums");const{ensureProjectIsInitialized}=await import("@stacksjs/utils");const isAppKeySet=await ensureProjectIsInitialized();if(!isAppKeySet){log.info("Your `APP_KEY` is not yet set");log.info("Generating application key...");const result=await runAction(Action.KeyGenerate);if(resultFailed(result)){await log.error("Failed to set random application key.",result.error);process.exit(1)}}}const commandsToLoad=getCommandsToLoad(args);await loadCommands(commandsToLoad,buddy);if(projectInstalled)await dynamicImports(buddy)}else{const{loadCommand}=await import("./lazy-commands.js");await loadCommand("version",buddy)}buddy.help();if(args.length===0&&process.stdin.isTTY&&!buddy.isNoInteraction){await showInteractiveMenu(buddy)}else{await parseOrExit(buddy)}}async function showInteractiveMenu(buddy){const{bold,green,intro}=await import("@stacksjs/cli");const{select}=await import("@stacksjs/cli");await intro("buddy");console.log(bold(green("What would you like to do?")));console.log("");const choice=await select({message:"Select a command:",choices:[{value:"dev",label:"Start development server"},{value:"build",label:"Build for production"},{value:"test",label:"Run tests"},{value:"list",label:"List all commands"},{value:"doctor",label:"Run health checks"},{value:"about",label:"Show system information"},{value:"help",label:"Show help"},{value:"exit",label:"Exit"}],initial:0});console.log("");if(choice==="exit"){process.exit(0)}else if(choice==="help"){buddy.outputHelp()}else{process.argv=["bun","buddy",choice];await parseOrExit(buddy)}}async function parseOrExit(buddy){try{await buddy.parse()}catch(error){const isUsageError=error?.name==="ClappError"||error?.isUsageError===true;if(!isUsageError)throw error;process.stderr.write(`${error.message}
6
6
  `);if(error.usage)process.stderr.write(`${error.usage}
7
7
  `);process.exit(typeof error.exitCode==="number"?error.exitCode:2)}}await main();async function dynamicImports(buddy){const{loadCommands}=await import("@stacksjs/cli");const commands=()=>buddy.commands??[];const before=commands().length;await loadCommands(buddy,{commandsDir:p.appPath("Commands"),registryPath:p.appPath("Commands.ts"),onError:(message,error)=>log.error(`${message}:`,error),onDebug:(message)=>log.debug(message)});const appCommandNames=new Set(commands().slice(before).flatMap((command)=>[command.name??"",...command.aliasNames??[]]));if(appCommandNames.has(requestedCommand)){const{injectGlobalAutoImports}=await import("@stacksjs/server");await injectGlobalAutoImports()}try{const listenerImport=await import(p.listenersPath("Console.ts"));if(typeof listenerImport.default==="function")listenerImport.default(buddy)}catch{}}}export function applyAliases(cli,signature,aliases){const name=signature.trim().split(/\s+/)[0];const commands=cli?.commands;const command=commands?.find((candidate)=>candidate.name===name);if(!command||typeof command.alias!=="function")return false;for(const alias of aliases)command.alias(alias);return true}
@@ -1,4 +1,4 @@
1
- import{homedir}from"node:os";import{resolve}from"node:path";import process from"node:process";import{bold,dim,green,onUnknownSubcommand}from"@stacksjs/cli";import{findProject,findProjectRoot,forgetProject,isProjectRoot,listProjects,pruneProjects,readProjectService,registerProject}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";function shortPath(path){const home=homedir();return path===home||path.startsWith(`${home}/`)?`~${path.slice(home.length)}`:path}function printProjects(options){const projects=listProjects();if(options.json){const rows=projects.map((project)=>({...project,exists:isProjectRoot(project.path),dashboard:readProjectService(project.path,"dashboard")?.url??null}));process.stdout.write(`${JSON.stringify(rows,null,2)}
1
+ import{homedir}from"node:os";import{resolve}from"node:path";import process from"node:process";import{bold,dim,green,onUnknownSubcommand}from"@stacksjs/cli";import{findProject,findProjectRoot,forgetProject,isProjectRoot,isTransientCheckout,listProjects,pruneProjects,readProjectService,registerProject}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";function shortPath(path){const home=homedir();return path===home||path.startsWith(`${home}/`)?`~${path.slice(home.length)}`:path}function printProjects(options){const projects=listProjects();if(options.json){const rows=projects.map((project)=>({...project,exists:isProjectRoot(project.path),dashboard:readProjectService(project.path,"dashboard")?.url??null}));process.stdout.write(`${JSON.stringify(rows,null,2)}
2
2
  `);return}if(options.quiet){for(const project of projects)process.stdout.write(`${project.path}
3
3
  `);return}if(projects.length===0){console.log("No Stacks projects on this machine's list yet.");console.log(dim("A project joins it the first time buddy runs inside it. To add the ones already on disk: buddy projects:scan"));return}const width=Math.max(...projects.map((project)=>project.name.length));for(const project of projects){const dashboard=readProjectService(project.path,"dashboard");const state=!isProjectRoot(project.path)?dim(" missing"):dashboard?` ${green("●")} ${dashboard.url}`:"";console.log(` ${bold(project.name.padEnd(width))} ${dim(shortPath(project.path))}${state}`)}}function fail(message){process.stderr.write(`${message}
4
- `);process.exit(ExitCode.FatalError)}function listedProject(query){const match=findProject(query);if(match.candidates.length>0)fail(`"${query}" matches more than one project: ${match.candidates.map((candidate)=>candidate.name).join(", ")}`);const listed=match.project&&listProjects().find((project)=>project.path===match.project.path);if(!listed)fail(`No project on the list matches "${query}".`);return listed}export function projects(buddy){const descriptions={list:"List the Stacks projects on this machine",add:"Add a Stacks project to this machine's list",remove:"Take a project off this machine's list (the project itself is not touched)",scan:"Find Stacks projects under a directory and add them to the list",prune:"Drop listed projects whose directory is gone",quiet:"Print only the paths, one per line",json:"Print the list as JSON"};for(const name of["projects","projects:list"]){buddy.command(name,descriptions.list).option("-q, --quiet",descriptions.quiet,{default:false}).option("--json",descriptions.json,{default:false}).action((options)=>{printProjects(options);process.exit(ExitCode.Success)})}buddy.command("projects:add [path]",descriptions.add).action((path)=>{const root=findProjectRoot(resolve(path??process.cwd()));const project=root?registerProject(root):null;if(!project)fail(`There is no Stacks project at ${resolve(path??process.cwd())}.`);console.log(`Added ${bold(project.name)} ${dim(shortPath(project.path))}`);process.exit(ExitCode.Success)});buddy.command("projects:remove <name>",descriptions.remove).alias("projects:forget").action((name)=>{const project=listedProject(name);forgetProject(project);console.log(`Removed ${bold(project.name)} from the list. ${dim(shortPath(project.path))} was not touched.`);process.exit(ExitCode.Success)});buddy.command("projects:scan [dir]",descriptions.scan).option("--depth <levels>","How many levels below the directory to look",{default:6}).action(async(dir,options)=>{const{findStacksProjects}=await import("@stacksjs/utils");const known=new Set(listProjects().map((project)=>project.path));const found=await findStacksProjects(dir?resolve(dir):undefined,{quiet:true,maxDepth:Number(options.depth)||6});const neverUsed=new Date(0);const added=found.map((root)=>registerProject(root,neverUsed)).filter((project)=>project!==null&&!known.has(project.path));for(const project of added)console.log(` ${green("+")} ${bold(project.name)} ${dim(shortPath(project.path))}`);console.log(`Found ${found.length} ${found.length===1?"project":"projects"}, ${added.length} new.`);process.exit(ExitCode.Success)});buddy.command("projects:prune",descriptions.prune).action(()=>{const removed=pruneProjects();for(const project of removed)console.log(` ${dim("-")} ${project.name} ${dim(shortPath(project.path))}`);console.log(removed.length===0?"Every listed project is still there.":`Removed ${removed.length} from the list.`);process.exit(ExitCode.Success)});onUnknownSubcommand(buddy,"projects")}
4
+ `);process.exit(ExitCode.FatalError)}function listedProject(query){const match=findProject(query);if(match.candidates.length>0)fail(`"${query}" matches more than one project: ${match.candidates.map((candidate)=>candidate.name).join(", ")}`);const listed=match.project&&listProjects().find((project)=>project.path===match.project.path);if(!listed)fail(`No project on the list matches "${query}".`);return listed}export function projects(buddy){const descriptions={list:"List the Stacks projects on this machine",add:"Add a Stacks project to this machine's list",remove:"Take a project off this machine's list (the project itself is not touched)",scan:"Find Stacks projects under a directory and add them to the list",prune:"Drop listed projects whose directory is gone",quiet:"Print only the paths, one per line",json:"Print the list as JSON"};for(const name of["projects","projects:list"]){buddy.command(name,descriptions.list).option("-q, --quiet",descriptions.quiet,{default:false}).option("--json",descriptions.json,{default:false}).action((options)=>{printProjects(options);process.exit(ExitCode.Success)})}buddy.command("projects:add [path]",descriptions.add).action((path)=>{const root=findProjectRoot(resolve(path??process.cwd()));const project=root?registerProject(root):null;if(!project)fail(`There is no Stacks project at ${resolve(path??process.cwd())}.`);console.log(`Added ${bold(project.name)} ${dim(shortPath(project.path))}`);process.exit(ExitCode.Success)});buddy.command("projects:remove <name>",descriptions.remove).alias("projects:forget").action((name)=>{const project=listedProject(name);forgetProject(project);console.log(`Removed ${bold(project.name)} from the list. ${dim(shortPath(project.path))} was not touched.`);process.exit(ExitCode.Success)});buddy.command("projects:scan [dir]",descriptions.scan).option("--depth <levels>","How many levels below the directory to look",{default:6}).action(async(dir,options)=>{const{findStacksProjects}=await import("@stacksjs/utils");const known=new Set(listProjects({includeMissing:true}).map((project)=>project.path));const discovered=await findStacksProjects(dir?resolve(dir):undefined,{quiet:true,maxDepth:Number(options.depth)||6});const found=discovered.filter((root)=>!isTransientCheckout(root));const copies=discovered.length-found.length;const neverUsed=new Date(0);const added=found.map((root)=>registerProject(root,neverUsed)).filter((project)=>project!==null&&!known.has(project.path));for(const project of added)console.log(` ${green("+")} ${bold(project.name)} ${dim(shortPath(project.path))}`);console.log(`Found ${found.length} ${found.length===1?"project":"projects"}, ${added.length} new.${copies>0?dim(` Left out ${copies} git ${copies===1?"worktree":"worktrees"} and temporary ${copies===1?"checkout":"checkouts"}.`):""}`);process.exit(ExitCode.Success)});buddy.command("projects:prune",descriptions.prune).action(()=>{const removed=pruneProjects();for(const project of removed)console.log(` ${dim("-")} ${project.name} ${dim(shortPath(project.path))}`);console.log(removed.length===0?"Every listed project is still there.":`Removed ${removed.length} from the list.`);process.exit(ExitCode.Success)});onUnknownSubcommand(buddy,"projects")}
@@ -11,6 +11,15 @@ export declare function isMachineCommand(command: string | undefined): boolean;
11
11
  * (`tsc --project`, for one).
12
12
  */
13
13
  export declare function findProjectSelector(args: string[], builtInCommands: ReadonlySet<string>): ProjectSelector | null;
14
+ /**
15
+ * `buddy --project shop migrate` as `buddy migrate --project shop`.
16
+ *
17
+ * In front of the command, `-p` can only mean the project, whatever the
18
+ * command later does with a `-p` of its own (`serve -p` is a port), so it is
19
+ * moved behind the command in its long form, where everything else reads it.
20
+ * Without a command after it there is nothing to move it behind.
21
+ */
22
+ export declare function projectAfterCommand(args: string[]): string[];
14
23
  /**
15
24
  * Decide where this invocation runs. No side effects: `launch` carries the
16
25
  * decision out.
@@ -21,7 +30,7 @@ export declare function planInvocation(context: InvocationContext): Invocation;
21
30
  * one that runs the command, with `process.argv` carrying what it should
22
31
  * parse; otherwise it does not return.
23
32
  */
24
- export declare function launch(context: InvocationContext): { root: string | null };
33
+ export declare function launch(context: InvocationContext): { root: string | null, projectInstalled: boolean };
25
34
  /**
26
35
  * Built-in commands whose `-p` is something other than `--project`.
27
36
  * `tests/launcher.test.ts` reads the command sources and fails when this list
package/dist/launcher.js CHANGED
@@ -1,2 +1,5 @@
1
- import{accessSync,constants,realpathSync}from"node:fs";import{join}from"node:path";import process from"node:process";import{findProject,findProjectRoot,isCompiledBinary,isVisitingCli,projectCliEntry,registerProject}from"@stacksjs/path";const MACHINE_COMMANDS=["new","create","projects","cd","daemon","dashboard"];const MACHINE_COMMAND_GROUPS=["projects:","daemon:"];export function isMachineCommand(command){if(command===undefined)return false;return MACHINE_COMMANDS.includes(command)||MACHINE_COMMAND_GROUPS.some((group)=>command.startsWith(group))}export const SHORT_P_IS_NOT_PROJECT=["build","make","preview","serve","serve:api","share"];export function findProjectSelector(args,builtInCommands){const command=args[0];if(command===undefined||!(builtInCommands.has(command)||builtInCommands.has(command.split(":")[0])))return null;const flags=SHORT_P_IS_NOT_PROJECT.includes(command)?["--project"]:["--project","-p"];for(let index=0;index<args.length;index++){const arg=args[index];if(arg==="--")break;for(const flag of flags){if(arg===flag){const value=args[index+1];if(value!==undefined&&!value.startsWith("-"))return{value,index:index+1,attached:null}}else if(arg.startsWith(`${flag}=`)&&arg.length>flag.length+1){return{value:arg.slice(flag.length+1),index,attached:flag}}}}return null}function samePath(a,b){try{return realpathSync(a)===realpathSync(b)}catch{return a===b}}function isExecutable(file){try{accessSync(file,constants.X_OK);return true}catch{return false}}export function planInvocation(context){const{args,cwd}=context;const command=args[0];if(isMachineCommand(command))return{kind:"run",root:findProjectRoot(cwd),args};const selector=findProjectSelector(args,context.builtInCommands);let root;let forwarded=args;if(selector){const match=findProject(selector.value,cwd);if(!match.project){return{kind:"refuse",message:match.candidates.length>0?`"${selector.value}" matches more than one Stacks project: ${match.candidates.map((project)=>project.name).join(", ")}. Name one of them in full, or give its path.`:`No Stacks project matches "${selector.value}". Run \`buddy projects\` to see the ones on this machine, or give a path.`}}root=match.project.path;forwarded=[...args];forwarded[selector.index]=selector.attached?`${selector.attached}=${root}`:root}else{root=findProjectRoot(cwd)}if(!root)return{kind:"run",root:null,args};if(context.handedRoot&&samePath(context.handedRoot,root)&&samePath(cwd,root))return{kind:"run",root,args:forwarded};if(isVisitingCli(root,context.main)){const shim=join(root,"buddy");return{kind:"handoff",root,command:isExecutable(shim)?[shim,...forwarded]:[process.execPath,projectCliEntry(root),...forwarded]}}if(!samePath(cwd,root)){const self=isCompiledBinary(context.main)?[process.execPath]:[process.execPath,...context.execArgv,context.main];return{kind:"handoff",root,command:[...self,...forwarded]}}return{kind:"run",root,args:forwarded}}export const HANDED_ROOT_ENV="STACKS_BUDDY_ROOT";function handOff(root,command){const env={...process.env,[HANDED_ROOT_ENV]:root};process.chdir(root);if(typeof process.execve==="function")process.execve(command[0],command,env);const child=Bun.spawnSync(command,{cwd:root,env,stdin:"inherit",stdout:"inherit",stderr:"inherit"});process.exit(child.exitCode??1)}export function launch(context){const invocation=planInvocation(context);if(invocation.kind==="refuse"){process.stderr.write(`${invocation.message}
2
- `);process.exit(1)}if(invocation.root)registerProject(invocation.root);if(invocation.kind==="handoff")handOff(invocation.root,invocation.command);if(invocation.args!==context.args)process.argv.splice(2,process.argv.length,...invocation.args);return{root:invocation.root}}
1
+ import{accessSync,constants,realpathSync}from"node:fs";import{basename,join}from"node:path";import process from"node:process";import{findProject,findProjectRoot,isCompiledBinary,isVisitingCli,noteProjectUsed,projectCliEntry}from"@stacksjs/path";import{isIsolatedRuntime,withoutIsolation}from"./runtime-flags";const MACHINE_COMMANDS=["new","create","projects","cd","daemon","dashboard"];const MACHINE_COMMAND_GROUPS=["projects:","daemon:"];export function isMachineCommand(command){if(command===undefined)return false;return MACHINE_COMMANDS.includes(command)||MACHINE_COMMAND_GROUPS.some((group)=>command.startsWith(group))}export const SHORT_P_IS_NOT_PROJECT=["build","make","preview","serve","serve:api","share"];export function findProjectSelector(args,builtInCommands){const command=args[0];if(command===undefined||!(builtInCommands.has(command)||builtInCommands.has(command.split(":")[0])))return null;const flags=SHORT_P_IS_NOT_PROJECT.includes(command)?["--project"]:["--project","-p"];for(let index=0;index<args.length;index++){const arg=args[index];if(arg==="--")break;for(const flag of flags){if(arg===flag){const value=args[index+1];if(value!==undefined&&!value.startsWith("-"))return{value,index:index+1,attached:null}}else if(arg.startsWith(`${flag}=`)&&arg.length>flag.length+1){return{value:arg.slice(flag.length+1),index,attached:flag}}}}return null}export function projectAfterCommand(args){const first=args[0];if(first==="--project"||first==="-p"){const[,value,command,...rest]=args;if(value!==undefined&&!value.startsWith("-")&&command!==undefined&&!command.startsWith("-"))return[command,"--project",value,...rest];return args}const attached=first?.match(/^(?:--project|-p)=(.+)$/);if(attached&&args[1]!==undefined&&!args[1].startsWith("-"))return[args[1],"--project",attached[1],...args.slice(2)];return args}function samePath(a,b){try{return realpathSync(a)===realpathSync(b)}catch{return a===b}}function isExecutable(file){try{accessSync(file,constants.X_OK);return true}catch{return false}}function runsWithoutInstall(args){return args[0]==="install"}export function planInvocation(context){const{cwd}=context;const args=projectAfterCommand(context.args);const command=args[0];if(isMachineCommand(command))return{kind:"run",root:findProjectRoot(cwd),args};const selector=args!==context.args?{value:args[2],index:2,attached:null}:findProjectSelector(args,context.builtInCommands);let root;let forwarded=args;if(selector){const match=findProject(selector.value,cwd);if(!match.project){return{kind:"refuse",message:match.candidates.length>0?`"${selector.value}" matches more than one Stacks project: ${match.candidates.map((project)=>project.name).join(", ")}. Name one of them in full, or give its path.`:`No Stacks project matches "${selector.value}". Run \`buddy projects\` to see the ones on this machine, or give a path.`}}root=match.project.path;forwarded=selector.attached?args.toSpliced(selector.index,1):args.toSpliced(selector.index-1,2)}else{root=findProjectRoot(cwd)}if(!root)return{kind:"run",root:null,args};if(projectCliEntry(root)===null&&!runsWithoutInstall(forwarded)){const name=basename(root);return{kind:"refuse",message:`${name} has nothing installed yet, so it has no buddy of its own to run this. Install its dependencies first:
2
+
3
+ buddy install --project ${name}
4
+ `}}const projectHasCli=projectCliEntry(root)!==null;const needsProjectConfig=projectHasCli&&isIsolatedRuntime(context.execArgv);if(context.handedRoot&&samePath(context.handedRoot,root)&&samePath(cwd,root)&&!needsProjectConfig)return{kind:"run",root,args:forwarded};if(isVisitingCli(root,context.main)){const shim=join(root,"buddy");return{kind:"handoff",root,command:isExecutable(shim)?[shim,...forwarded]:[process.execPath,projectCliEntry(root),...forwarded]}}if(!samePath(cwd,root)||needsProjectConfig){const execArgv=projectHasCli?withoutIsolation(context.execArgv):context.execArgv;const self=isCompiledBinary(context.main)?[process.execPath]:[process.execPath,...execArgv,context.main];return{kind:"handoff",root,command:[...self,...forwarded]}}return{kind:"run",root,args:forwarded}}export const HANDED_ROOT_ENV="STACKS_BUDDY_ROOT";function handOff(root,command){const env={...process.env,[HANDED_ROOT_ENV]:root};process.chdir(root);if(typeof process.execve==="function")process.execve(command[0],command,env);const child=Bun.spawnSync(command,{cwd:root,env,stdin:"inherit",stdout:"inherit",stderr:"inherit"});process.exit(child.exitCode??1)}export function launch(context){const invocation=planInvocation(context);if(invocation.kind==="refuse"){process.stderr.write(`${invocation.message}
5
+ `);process.exit(1)}if(invocation.root)noteProjectUsed(invocation.root);if(invocation.kind==="handoff")handOff(invocation.root,invocation.command);if(invocation.args.length!==context.args.length||invocation.args.some((arg,index)=>arg!==context.args[index]))process.argv.splice(2,process.argv.length,...invocation.args);return{root:invocation.root,projectInstalled:invocation.root===null||projectCliEntry(invocation.root)!==null}}
@@ -1 +1 @@
1
- import{FEATURE_NAMES}from"@stacksjs/features";const APP_KEY_OPTIONAL_COMMANDS=["env","projects","cd","daemon","dashboard","desktop:apple","build","workflow","link:core","unlink:core","publish:core","unpublish:core","publish:defaults","unpublish:defaults","lint","docs","release","lint:fix","test","test:types","test:unit","test:feature","typecheck","types:fix","types:generate","clean","fresh","about","ai:context","doctor","list","setup","setup:ssl","setup:oh-my-zsh","deploy","serve","new","create","upgrade","update","migrate","seed","generate","make","key:generate","scaffold:crud"];export function shouldSkipAppKeyCheck(requestedCommand,mode={}){return Boolean(mode.isHelpFlag||mode.isHelpMode||FEATURE_NAMES.some((feature)=>requestedCommand===`${feature}:install`||requestedCommand===`${feature}:uninstall`)||APP_KEY_OPTIONAL_COMMANDS.some((command)=>requestedCommand===command||requestedCommand.startsWith(`${command}:`)))}
1
+ import{FEATURE_NAMES}from"@stacksjs/features";const APP_KEY_OPTIONAL_COMMANDS=["env","projects","cd","daemon","dashboard","install","desktop:apple","build","workflow","link:core","unlink:core","publish:core","unpublish:core","publish:defaults","unpublish:defaults","lint","docs","release","lint:fix","test","test:types","test:unit","test:feature","typecheck","types:fix","types:generate","clean","fresh","about","ai:context","doctor","list","setup","setup:ssl","setup:oh-my-zsh","deploy","serve","new","create","upgrade","update","migrate","seed","generate","make","key:generate","scaffold:crud"];export function shouldSkipAppKeyCheck(requestedCommand,mode={}){return Boolean(mode.isHelpFlag||mode.isHelpMode||FEATURE_NAMES.some((feature)=>requestedCommand===`${feature}:install`||requestedCommand===`${feature}:uninstall`)||APP_KEY_OPTIONAL_COMMANDS.some((command)=>requestedCommand===command||requestedCommand.startsWith(`${command}:`)))}
@@ -0,0 +1,29 @@
1
+ /** Whether this process was started the way the executable starts it. */
2
+ export declare function isIsolatedRuntime(execArgv: readonly string[]): boolean;
3
+ /** `execArgv` for a restart that should read the project's config again. */
4
+ export declare function withoutIsolation(execArgv: readonly string[]): string[];
5
+ /**
6
+ * How the published `buddy` executable starts Bun.
7
+ *
8
+ * Bun reads `bunfig.toml` from the directory it starts in and runs that file's
9
+ * preloads before the first line of the CLI. For a `buddy` installed once for
10
+ * the machine, that directory is wherever it was typed: inside a project, Bun
11
+ * ran the project's env plugin and preloader in a process that only decides
12
+ * which `buddy` should run the command and then hands over to it, and the
13
+ * process it hands to does all of that again. In a project with nothing
14
+ * installed it was worse. The preloads named packages that are not there, Bun
15
+ * auto-installed them from the network at whatever version it picked, and a
16
+ * trivial command took five seconds before buddy's own code ran.
17
+ *
18
+ * So the executable starts Bun with no config file and no auto-install: its
19
+ * own dependencies are installed beside it, and the project's config belongs
20
+ * to the process started in the project. When the CLI turns out to be the
21
+ * project's own after all (`node_modules/.bin/buddy` in an npm script), the
22
+ * launcher restarts it in the root without these flags, under the project's
23
+ * config.
24
+ *
25
+ * No imports: the build reads this too.
26
+ */
27
+ export declare const ISOLATED_RUNTIME_FLAGS: readonly ['--config=/dev/null', '--no-install'];
28
+ /** `env -S` splits the line into arguments, on macOS and on Linux alike. */
29
+ export declare const CLI_SHEBANG: string;
@@ -0,0 +1 @@
1
+ export const ISOLATED_RUNTIME_FLAGS=["--config=/dev/null","--no-install"];export const CLI_SHEBANG=`#!/usr/bin/env -S bun ${ISOLATED_RUNTIME_FLAGS.join(" ")}`;export function isIsolatedRuntime(execArgv){return ISOLATED_RUNTIME_FLAGS.every((flag)=>execArgv.includes(flag))}export function withoutIsolation(execArgv){return execArgv.filter((flag)=>!ISOLATED_RUNTIME_FLAGS.includes(flag))}
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/buddy",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.75.623",
5
+ "version": "0.75.625",
6
6
  "description": "Meet Buddy. The Stacks runtime.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -95,71 +95,71 @@
95
95
  "prepublishOnly": "bun run build"
96
96
  },
97
97
  "dependencies": {
98
- "@stacksjs/actions": "0.75.623",
99
- "@stacksjs/docs": "0.75.623",
100
- "@stacksjs/ai": "0.75.623",
101
- "@stacksjs/alias": "0.75.623",
102
- "@stacksjs/analytics": "0.75.623",
103
- "@stacksjs/api": "0.75.623",
104
- "@stacksjs/arrays": "0.75.623",
105
- "@stacksjs/auth": "0.75.623",
106
- "@stacksjs/browser-extension": "0.75.623",
107
- "@stacksjs/build": "0.75.623",
98
+ "@stacksjs/actions": "0.75.625",
99
+ "@stacksjs/docs": "0.75.625",
100
+ "@stacksjs/ai": "0.75.625",
101
+ "@stacksjs/alias": "0.75.625",
102
+ "@stacksjs/analytics": "0.75.625",
103
+ "@stacksjs/api": "0.75.625",
104
+ "@stacksjs/arrays": "0.75.625",
105
+ "@stacksjs/auth": "0.75.625",
106
+ "@stacksjs/browser-extension": "0.75.625",
107
+ "@stacksjs/build": "0.75.625",
108
108
  "@stacksjs/bumpx": "^0.2.32",
109
- "@stacksjs/cache": "0.75.623",
110
- "@stacksjs/chat": "0.75.623",
109
+ "@stacksjs/cache": "0.75.625",
110
+ "@stacksjs/chat": "0.75.625",
111
111
  "@stacksjs/clapp": "^0.2.17",
112
- "@stacksjs/cli": "0.75.623",
113
- "@stacksjs/cloud": "0.75.623",
114
- "@stacksjs/cms": "0.75.623",
115
- "@stacksjs/collections": "0.75.623",
116
- "@stacksjs/commerce": "0.75.623",
117
- "@stacksjs/config": "0.75.623",
118
- "@stacksjs/database": "0.75.623",
119
- "@stacksjs/desktop-build": "0.75.623",
120
- "@stacksjs/dns": "0.75.623",
112
+ "@stacksjs/cli": "0.75.625",
113
+ "@stacksjs/cloud": "0.75.625",
114
+ "@stacksjs/cms": "0.75.625",
115
+ "@stacksjs/collections": "0.75.625",
116
+ "@stacksjs/commerce": "0.75.625",
117
+ "@stacksjs/config": "0.75.625",
118
+ "@stacksjs/database": "0.75.625",
119
+ "@stacksjs/desktop-build": "0.75.625",
120
+ "@stacksjs/dns": "0.75.625",
121
121
  "@stacksjs/dnsx": "^0.2.3",
122
- "@stacksjs/email": "0.75.623",
123
- "@stacksjs/enums": "0.75.623",
124
- "@stacksjs/env": "0.75.623",
125
- "@stacksjs/error-handling": "0.75.623",
126
- "@stacksjs/events": "0.75.623",
127
- "@stacksjs/features": "0.75.623",
128
- "@stacksjs/git": "0.75.623",
122
+ "@stacksjs/email": "0.75.625",
123
+ "@stacksjs/enums": "0.75.625",
124
+ "@stacksjs/env": "0.75.625",
125
+ "@stacksjs/error-handling": "0.75.625",
126
+ "@stacksjs/events": "0.75.625",
127
+ "@stacksjs/features": "0.75.625",
128
+ "@stacksjs/git": "0.75.625",
129
129
  "@stacksjs/gitit": "^0.2.5",
130
- "@stacksjs/health": "0.75.623",
131
- "@stacksjs/hq": "0.75.623",
130
+ "@stacksjs/health": "0.75.625",
131
+ "@stacksjs/hq": "0.75.625",
132
132
  "@stacksjs/httx": "^0.1.10",
133
- "@stacksjs/image": "0.75.623",
134
- "@stacksjs/lint": "0.75.623",
135
- "@stacksjs/logging": "0.75.623",
136
- "@stacksjs/notifications": "0.75.623",
137
- "@stacksjs/objects": "0.75.623",
138
- "@stacksjs/orm": "0.75.623",
139
- "@stacksjs/path": "0.75.623",
140
- "@stacksjs/payments": "0.75.623",
141
- "@stacksjs/realtime": "0.75.623",
142
- "@stacksjs/router": "0.75.623",
133
+ "@stacksjs/image": "0.75.625",
134
+ "@stacksjs/lint": "0.75.625",
135
+ "@stacksjs/logging": "0.75.625",
136
+ "@stacksjs/notifications": "0.75.625",
137
+ "@stacksjs/objects": "0.75.625",
138
+ "@stacksjs/orm": "0.75.625",
139
+ "@stacksjs/path": "0.75.625",
140
+ "@stacksjs/payments": "0.75.625",
141
+ "@stacksjs/realtime": "0.75.625",
142
+ "@stacksjs/router": "0.75.625",
143
143
  "@stacksjs/rpx": "^0.11.54",
144
- "@stacksjs/scheduler": "0.75.623",
145
- "@stacksjs/search-engine": "0.75.623",
146
- "@stacksjs/security": "0.75.623",
147
- "@stacksjs/server": "0.75.623",
148
- "@stacksjs/sites": "0.75.623",
149
- "@stacksjs/skills": "0.75.623",
150
- "@stacksjs/socials": "0.75.623",
151
- "@stacksjs/storage": "0.75.623",
152
- "@stacksjs/strings": "0.75.623",
144
+ "@stacksjs/scheduler": "0.75.625",
145
+ "@stacksjs/search-engine": "0.75.625",
146
+ "@stacksjs/security": "0.75.625",
147
+ "@stacksjs/server": "0.75.625",
148
+ "@stacksjs/sites": "0.75.625",
149
+ "@stacksjs/skills": "0.75.625",
150
+ "@stacksjs/socials": "0.75.625",
151
+ "@stacksjs/storage": "0.75.625",
152
+ "@stacksjs/strings": "0.75.625",
153
153
  "@stacksjs/stx": "^0.2.908",
154
- "@stacksjs/testing": "0.75.623",
155
- "@stacksjs/tinker": "0.75.623",
154
+ "@stacksjs/testing": "0.75.625",
155
+ "@stacksjs/tinker": "0.75.625",
156
156
  "@stacksjs/tlsx": "^0.13.19",
157
- "@stacksjs/ts-cloud": "^0.16.143",
158
- "@stacksjs/tunnel": "0.75.623",
159
- "@stacksjs/types": "0.75.623",
160
- "@stacksjs/ui": "0.75.623",
161
- "@stacksjs/utils": "0.75.623",
162
- "@stacksjs/validation": "0.75.623",
157
+ "@stacksjs/ts-cloud": "^0.16.144",
158
+ "@stacksjs/tunnel": "0.75.625",
159
+ "@stacksjs/types": "0.75.625",
160
+ "@stacksjs/ui": "0.75.625",
161
+ "@stacksjs/utils": "0.75.625",
162
+ "@stacksjs/validation": "0.75.625",
163
163
  "ajv": "^8.20.0",
164
164
  "ajv-formats": "^3.0.1",
165
165
  "bun-plugin-stx": "^0.2.908",