@stacksjs/buddy 0.75.489 → 0.75.492

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 +1 @@
1
- import{chmodSync,cpSync,existsSync,readFileSync,readdirSync,rmSync,writeFileSync}from"node:fs";import process from"node:process";import{runAction}from"@stacksjs/actions";import{bold,cyan,dim,intro,log,onUnknownSubcommand,runCommand}from"@stacksjs/cli";import{Action}from"@stacksjs/enums";import{relative,resolve}from"@stacksjs/path";import{isFolder}from"@stacksjs/storage";import{ExitCode}from"@stacksjs/types";import{uninstallAllFeatures}from"./features";import{ensurePantryDependencies,ensurePantryInstalled,optimizePantryDeps}from"./setup";import{resultFailed}from"../result";import{appIdentity,applyAppAgentsTemplate,applyAppChangelogTemplate,applyAppEnvTemplate,applyAppPackageTemplate,removeFrameworkLicense,renderTemplate}from"../scaffold-app";import{applyAppSiteTemplate}from"../scaffold-site";import{adoptPackagedDefaults,applyAppPackageScripts,applyPackageAppTsconfig,pruneFrameworkOnlyFiles,rewriteCoreContentPaths,stripFrameworkManifestCredits}from"../scaffold-package-app";import{fetchPublishedVersions}from"../registry";import{ensureAuthRoutesEnv}from"../minimal-routes";import{scaffoldDesktopApp}from"../scaffold-desktop";export function create(buddy){const descriptions={name:"The name of the project",command:"Create a new Stacks project",ui:"Are you building a UI?",components:"Are you building UI components?",webComponents:"Automagically built optimized custom elements/web components?",views:"How about views?",functions:"Are you developing functions/composables?",api:"Are you building an API?",database:"Do you need a database?",notifications:"Do you need notifications? e.g. email, SMS, push or chat notifications",cache:"Do you need caching?",email:"Do you need email?",project:"Target a specific project",minimal:"Skip optional feature bundles (cms, commerce, dashboard, marketing, monitoring, realtime, queue) - bare-bones API/SPA starter that can re-add them later via `./buddy <feature>:install`.",withCore:"Keep the framework vendored in `storage/framework/core` as a Bun workspace, for working ON Stacks. Apps that only work WITH Stacks want the default, which resolves every @stacksjs/* package from npm.",vendorDefaults:"Commit a copy of the framework defaults in `storage/framework/defaults` instead of linking it to node_modules/@stacksjs/defaults. Implied by --with-core.",verbose:"Enable verbose output"};buddy.command("new [name]",descriptions.command).alias("create").option("-n, --name [name]",descriptions.name,{default:!1}).option("-u, --ui",descriptions.ui,{default:!0}).option("-c, --components",descriptions.components,{default:!0}).option("-w, --web-components",descriptions.webComponents,{default:!0}).option("-p, --views",descriptions.views,{default:!0}).option("-f, --functions",descriptions.functions,{default:!0}).option("-a, --api",descriptions.api,{default:!0}).option("-d, --database",descriptions.database,{default:!0}).option("-ca, --cache",descriptions.cache,{default:!1}).option("-e, --email",descriptions.email,{default:!1}).option("-P, --project [project]",descriptions.project,{default:!1}).option("-m, --minimal",descriptions.minimal,{default:!1}).option("--native","Create a minimal offline Craft desktop app",{default:!1}).option("--desktop","Also make it a native Mac app: stx screens drawn by AppKit, with the API running inside the app (config/desktop.ts, macos.agent)",{default:!1}).option("--adopt","Integrate an existing native app without replacing its source (requires --native)",{default:!1}).option("--with-core",descriptions.withCore,{default:!1}).option("--vendor-defaults",descriptions.vendorDefaults,{default:!1}).option("--no-provision","Install JavaScript dependencies without provisioning system packages").option("--verbose",descriptions.verbose,{default:!1}).action(async(name,options)=>{log.debug("Running `buddy new <name>` ...",options);const startTime=await intro("buddy new");name=name??options.name;const path=resolve(process.cwd(),name??".");if(options.adopt&&!options.native)throw Error("--adopt requires --native");if(options.desktop&&options.native)throw Error("--desktop makes a Stacks app with a native Mac app; --native makes a standalone Craft app. Choose one.");if(options.native){const{scaffoldNativeProject}=await import("../native-project"),{version}=await import("../../package.json"),{latest}=await fetchPublishedVersions("@stacksjs/stx");if(!latest)throw Error("The registry has no published stx version.");scaffoldNativeProject(path,{adopt:options.adopt,buddyVersion:version,stxVersion:latest});const installed=await runCommand(["bun","install"],{cwd:path});if(resultFailed(installed))throw installed.error;log.success(`Native app ready at ${path}. Run ./buddy dev to launch.`);await log.flush();return}isFolderCheck(path);await onlineCheck();const result=await download(name,path,options);if(resultFailed(result)){await log.error(result.error);process.exit(ExitCode.FatalError)}ensureExecutableScripts(path);applyAppVcsTemplate(path);applyAppConfigTemplate(path);applyAppEnv(path);applyAppPackage(path);applyAppReadme(path);applyAppAgents(path);replaceFrameworkSite(path);removeFrameworkTests(path);await generatePantryDeps(path);await ensureEnv(path,options);if(options.minimal)await stripFeatures(path);await install(path,options);if(!options.withCore){trimFrameworkOnlyFiles(path);await unvendorCore(path,options);applyPackageAppTsconfig(path);if(!options.vendorDefaults)linkFrameworkDefaults(path)}if(options.minimal||!options.withCore&&!options.vendorDefaults)await regenerateAutoImports(path,options);if(options.desktop){const written=scaffoldDesktopApp(path,appIdentity(path));log.success(`Added the Mac app (${written.join(", ")}). Run ${cyan("bun run dev:desktop")} to open it.`)}if(startTime){const time=performance.now()-startTime;log.success(dim(`[${time.toFixed(2)}ms] Completed`))}log.info(bold("Welcome to the Stacks Framework! \u269B\uFE0F"));log.info(`Get started: ${cyan(`cd ${name}`)} and then ${cyan("./buddy dev")}`);log.info(`Run ${cyan("./buddy doctor")} anytime to check your setup`);log.info("To learn more, visit https://stacksjs.com");await log.flush();process.exit(ExitCode.Success)});onUnknownSubcommand(buddy,"new")}export function scaffoldTargetOccupants(path){if(!isFolder(path))return[];return readdirSync(path).filter((entry)=>entry!==".git")}function isFolderCheck(path){if(scaffoldTargetOccupants(path).length===0)return;console.error(`Path ${path} already exists`);process.exit(ExitCode.FatalError)}async function onlineCheck(){const offline=await offlineReason();if(!offline)return;log.info(`It appears you are disconnected from the internet (github.com: ${offline}).`);log.info("Creating a new project requires a brief internet connection to download the template and install dependencies.");await log.flush();process.exit(ExitCode.FatalError)}export async function offlineReason(fetcher=fetch){try{await fetcher("https://github.com",{method:"HEAD",signal:AbortSignal.timeout(3000)});return null}catch(error){return error instanceof Error?error.message:String(error)}}export async function templateRef(fetchVersions=fetchPublishedVersions){try{const{latest}=await fetchVersions("stacks");return latest?`v${latest}`:null}catch{return null}}export function templateSpec(ref){return ref?`gh:stacksjs/stacks#${ref}`:"gh:stacksjs/stacks"}async function download(name,path,_options){log.info("Setting up your stack.");const ref=await templateRef();try{const{downloadTemplate}=await import("@stacksjs/gitit");try{await downloadTemplate(templateSpec(ref),{dir:name,force:!0})}catch(error){if(!ref)throw error;log.warn(`No ${ref} tag to scaffold from (${error instanceof Error?error.message:String(error)}).`);log.info("Falling back to the default branch. If this app does not typecheck, that gap is why.");await downloadTemplate(templateSpec(null),{dir:name,force:!0})}log.success(`Successfully scaffolded your project at ${cyan(path)}`);return{isErr:!1}}catch(error){return{isErr:!0,error:error instanceof Error?error.message:String(error)}}}function applyAppVcsTemplate(path){const source=resolve(path,"storage/framework/defaults/vcs/github"),destination=resolve(path,".github");if(!existsSync(source)){log.warn("No app CI template found at storage/framework/defaults/vcs/github - leaving .github as downloaded.");return}log.info("Installing app-shaped GitHub workflows...");try{rmSync(destination,{recursive:!0,force:!0});cpSync(source,destination,{recursive:!0});log.success("App CI installed")}catch(error){log.warn(`Could not install the app CI template: ${error instanceof Error?error.message:String(error)}`)}}function applyAppConfigTemplate(path){const source=resolve(path,"storage/framework/defaults/scaffold/config"),destination=resolve(path,"config");if(!existsSync(source)){log.warn("No app config template found at storage/framework/defaults/scaffold/config - leaving config as downloaded.");return}const identity=appIdentity(path);log.info("Installing app-safe infrastructure configuration...");try{for(const file of readdirSync(source)){if(!file.endsWith(".ts"))continue;const template=readFileSync(resolve(source,file),"utf8");writeFileSync(resolve(destination,file),renderTemplate(template,identity))}log.success("App-safe infrastructure configuration installed")}catch(error){log.warn(`Could not install the app config template: ${error instanceof Error?error.message:String(error)}`)}}function applyAppEnv(path){try{const changed=applyAppEnvTemplate(path,appIdentity(path));if(changed.length>0)log.success(`Named the app in .env.example (${changed.join(", ")})`)}catch(error){log.warn(`Could not name the app in .env.example: ${error instanceof Error?error.message:String(error)}`)}}function applyAppPackage(path){try{const identity=appIdentity(path),changed=applyAppPackageTemplate(path,identity);if(changed.length>0)log.success(`Named the app in package.json (${changed.join(", ")})`);if(applyAppChangelogTemplate(path,identity))log.success("Started the app its own CHANGELOG.md");if(removeFrameworkLicense(path))log.success("Removed the framework's LICENSE.md - choose the app's own licence")}catch(error){log.warn(`Could not name the app in package.json: ${error instanceof Error?error.message:String(error)}`)}}function applyAppAgents(path){try{if(applyAppAgentsTemplate(path))log.success("AGENTS.md no longer tells agents to publish as the framework's author")}catch(error){log.warn(`Could not update AGENTS.md: ${error instanceof Error?error.message:String(error)}`)}}function applyAppReadme(path){const source=resolve(path,"storage/framework/defaults/scaffold/README.md");if(!existsSync(source))return;try{writeFileSync(resolve(path,"README.md"),renderTemplate(readFileSync(source,"utf8"),appIdentity(path)))}catch(error){log.warn(`Could not write the app README: ${error instanceof Error?error.message:String(error)}`)}}function replaceFrameworkSite(path){log.info("Replacing the stacksjs.com site with a starter page...");try{const removed=applyAppSiteTemplate(path);log.success(`Starter page installed (${removed.length} stacksjs.com path${removed.length===1?"":"s"} removed)`)}catch(error){log.warn(`Could not install the starter page: ${error instanceof Error?error.message:String(error)}`)}}function removeFrameworkTests(path){const tests=resolve(path,"tests");if(!existsSync(tests))return;log.info("Removing the framework's own test suite...");for(const entry of readdirSync(tests)){if(entry==="setup.ts")continue;rmSync(resolve(tests,entry),{recursive:!0,force:!0})}log.success("App starts with a clean test suite")}function ensureExecutableScripts(path){for(const script of["buddy","bootstrap"])try{chmodSync(resolve(path,script),493)}catch{}}async function ensureEnv(path,options){log.info("Ensuring your environment is ready...");if(options.provision===!1){const installed=await runCommand(["bun","install"],{cwd:path});if(resultFailed(installed))throw installed.error;log.success("JavaScript dependencies installed; system provisioning skipped");return}await ensurePantryInstalled();await ensurePantryDependencies(path);log.success("Environment is ready")}async function install(path,options){log.info("Installing & setting up Stacks");log.info("Copying .env.example \u2192 .env");let result=await runCommand("cp .env.example .env",{...options,cwd:path});if(resultFailed(result)){await log.error(result.error);process.exit(ExitCode.FatalError)}log.info("Removing template-encrypted env files...");const{rm}=await import("node:fs/promises");for(const stale of[".env.development",".env.staging",".env.production",".env.keys"])await rm(`${path}/${stale}`,{force:!0});log.info("Generating application key...");const keyResult=await runAction(Action.KeyGenerate,{...options,cwd:path});if(resultFailed(keyResult)){await log.error(keyResult.error);process.exit(ExitCode.FatalError)}if(existsSync(resolve(path,".git")))log.info("Existing git repository detected, skipping git init");else{log.info("Initializing git repository...");result=await runCommand("git init",{...options,cwd:path});if(resultFailed(result)){await log.error(result.error);process.exit(ExitCode.FatalError)}}log.success("Installed & set-up \uD83D\uDE80")}async function unvendorCore(path,options){log.info("Resolving the framework from npm (pass --with-core to keep it vendored)...");const result=await runCommand("./buddy unpublish:core --all --force",{...options,cwd:path});if(resultFailed(result)){const reason=result.error instanceof Error?result.error.stack??result.error.message:String(result.error??"").trim();log.error("Could not resolve the framework from npm.");log.error(reason.length>0?reason:"The step failed without reporting a reason.");log.error("");log.error(`The project at ${path} is half converted: the vendored framework has been`);log.error("removed and the published packages are not in place yet, so ./buddy cannot");log.error("boot there. Finish it by hand with:");log.error("");await log.error(` cd ${path} && rm -f node_modules/stacks && bun install`);await log.error("");await log.error("Or start over with `--with-core` to keep the framework vendored.");process.exit(ExitCode.FatalError)}log.success("Framework resolved from npm")}async function generatePantryDeps(path){try{if(await optimizePantryDeps(path))rmSync(resolve(path,"deps.yml"),{force:!0})}catch(error){log.warn(`Could not generate deps.yaml from config/deps.ts, keeping the template's deps.yml: ${error instanceof Error?error.message:String(error)}`)}}function trimFrameworkOnlyFiles(path){try{const removed=pruneFrameworkOnlyFiles(path),scripts=applyAppPackageScripts(path);rewriteCoreContentPaths(path);stripFrameworkManifestCredits(path);log.success(`Removed ${removed.length} framework-only path${removed.length===1?"":"s"} and ${scripts.removed.length} framework-only script${scripts.removed.length===1?"":"s"}`)}catch(error){log.warn(`Could not remove the framework-only files: ${error instanceof Error?error.message:String(error)}`)}}function linkFrameworkDefaults(path){log.info("Linking the framework defaults from node_modules (pass --vendor-defaults to commit a copy)...");try{const adopted=adoptPackagedDefaults(path);log.success(`storage/framework/defaults now links to ${relative(path,adopted.packageRoot)}`)}catch(error){log.warn(`Could not move the framework defaults to node_modules: ${error instanceof Error?error.message:String(error)}`)}}async function regenerateAutoImports(path,options){const result=await runCommand("./buddy generate --types",{...options,cwd:path});if(resultFailed(result))log.warn("Could not regenerate the auto-import barrels. Run `./buddy generate --types` in the project before `./buddy dev`.")}async function stripFeatures(path){log.info("Stripping optional feature bundles (--minimal)...");const results=await uninstallAllFeatures({root:path}),authEnv=ensureAuthRoutesEnv(path);if(authEnv.length>0)log.info(` - kept the auth routes mounted (STACKS_DEFAULT_ROUTES=auth in ${authEnv.join(", ")})`);let strippedAny=!1;for(const{feature,configOutcome,filesRemoved}of results)if(configOutcome==="flipped"||filesRemoved.length>0){strippedAny=!0;const fileSummary=filesRemoved.length>0?` (${filesRemoved.length} path${filesRemoved.length===1?"":"s"})`:"";log.info(` - ${feature}${fileSummary}`)}if(!strippedAny)log.info(" \u2192 no feature scaffolding present; nothing to strip.");else log.success("Minimal skeleton ready - run `./buddy <feature>:install` to add features back.")}
1
+ import{chmodSync,cpSync,existsSync,readFileSync,readdirSync,rmSync,writeFileSync}from"node:fs";import process from"node:process";import{runAction}from"@stacksjs/actions";import{bold,cyan,dim,intro,log,onUnknownSubcommand,runCommand}from"@stacksjs/cli";import{Action}from"@stacksjs/enums";import{isCompiledBinary,relative,resolve}from"@stacksjs/path";import{isFolder}from"@stacksjs/storage";import{ExitCode}from"@stacksjs/types";import{uninstallAllFeatures}from"./features";import{attemptPantryDependencies,optimizePantryDeps}from"./setup";import{resultFailed}from"../result";import{appIdentity,applyAppAgentsTemplate,applyAppChangelogTemplate,applyAppEnvTemplate,applyAppPackageTemplate,removeFrameworkLicense,renderTemplate}from"../scaffold-app";import{applyAppSiteTemplate}from"../scaffold-site";import{adoptPackagedDefaults,applyAppPackageScripts,applyPackageAppTsconfig,pruneFrameworkOnlyFiles,rewriteCoreContentPaths,stripFrameworkManifestCredits}from"../scaffold-package-app";import{fetchPublishedVersions}from"../registry";import{ensureAuthRoutesEnv}from"../minimal-routes";import{scaffoldDesktopApp}from"../scaffold-desktop";import{bunExecutable,failureReason,installScaffoldDependencies}from"../scaffold-dependencies";export function create(buddy){const descriptions={name:"The name of the project",command:"Create a new Stacks project",ui:"Are you building a UI?",components:"Are you building UI components?",webComponents:"Automagically built optimized custom elements/web components?",views:"How about views?",functions:"Are you developing functions/composables?",api:"Are you building an API?",database:"Do you need a database?",notifications:"Do you need notifications? e.g. email, SMS, push or chat notifications",cache:"Do you need caching?",email:"Do you need email?",project:"Target a specific project",minimal:"Skip optional feature bundles (cms, commerce, dashboard, marketing, monitoring, realtime, queue) - bare-bones API/SPA starter that can re-add them later via `./buddy <feature>:install`.",withCore:"Keep the framework vendored in `storage/framework/core` as a Bun workspace, for working ON Stacks. Apps that only work WITH Stacks want the default, which resolves every @stacksjs/* package from npm.",vendorDefaults:"Commit a copy of the framework defaults in `storage/framework/defaults` instead of linking it to node_modules/@stacksjs/defaults. Implied by --with-core.",verbose:"Enable verbose output"};buddy.command("new [name]",descriptions.command).alias("create").option("-n, --name [name]",descriptions.name,{default:!1}).option("-u, --ui",descriptions.ui,{default:!0}).option("-c, --components",descriptions.components,{default:!0}).option("-w, --web-components",descriptions.webComponents,{default:!0}).option("-p, --views",descriptions.views,{default:!0}).option("-f, --functions",descriptions.functions,{default:!0}).option("-a, --api",descriptions.api,{default:!0}).option("-d, --database",descriptions.database,{default:!0}).option("-ca, --cache",descriptions.cache,{default:!1}).option("-e, --email",descriptions.email,{default:!1}).option("-P, --project [project]",descriptions.project,{default:!1}).option("-m, --minimal",descriptions.minimal,{default:!1}).option("--native","Create a minimal offline Craft desktop app",{default:!1}).option("--desktop","Also make it a native Mac app: stx screens drawn by AppKit, with the API running inside the app (config/desktop.ts, macos.agent)",{default:!1}).option("--adopt","Integrate an existing native app without replacing its source (requires --native)",{default:!1}).option("--with-core",descriptions.withCore,{default:!1}).option("--vendor-defaults",descriptions.vendorDefaults,{default:!1}).option("--no-provision","Install JavaScript dependencies without provisioning system packages").option("--verbose",descriptions.verbose,{default:!1}).action(async(name,options)=>{log.debug("Running `buddy new <name>` ...",options);const startTime=await intro("buddy new");name=name??options.name;const path=resolve(process.cwd(),name??".");if(options.adopt&&!options.native)throw Error("--adopt requires --native");if(options.desktop&&options.native)throw Error("--desktop makes a Stacks app with a native Mac app; --native makes a standalone Craft app. Choose one.");if(options.native){const{scaffoldNativeProject}=await import("../native-project"),{version}=await import("../../package.json"),{latest}=await fetchPublishedVersions("@stacksjs/stx");if(!latest)throw Error("The registry has no published stx version.");scaffoldNativeProject(path,{adopt:options.adopt,buddyVersion:version,stxVersion:latest});const installed=await runCommand(["bun","install"],{cwd:path});if(resultFailed(installed))throw installed.error;log.success(`Native app ready at ${path}. Run ./buddy dev to launch.`);await log.flush();return}isFolderCheck(path);await onlineCheck();const result=await download(name,path,options);if(resultFailed(result)){await log.error(result.error);process.exit(ExitCode.FatalError)}ensureExecutableScripts(path);applyAppVcsTemplate(path);applyAppConfigTemplate(path);applyAppEnv(path);applyAppPackage(path);applyAppReadme(path);applyAppAgents(path);replaceFrameworkSite(path);removeFrameworkTests(path);await generatePantryDeps(path);const missingSystemDependencies=await ensureEnv(path,options);if(options.minimal)await stripFeatures(path);await install(path,options);if(!options.withCore){trimFrameworkOnlyFiles(path);await unvendorCore(path,options,missingSystemDependencies!==null);applyPackageAppTsconfig(path);if(!options.vendorDefaults)linkFrameworkDefaults(path)}if(options.minimal||!options.withCore&&!options.vendorDefaults)await regenerateAutoImports(path,options);if(options.desktop){const written=scaffoldDesktopApp(path,appIdentity(path));log.success(`Added the Mac app (${written.join(", ")}). Run ${cyan("bun run dev:desktop")} to open it.`)}if(missingSystemDependencies!==null){log.warn(`The app is scaffolded at ${path}, but Pantry could not install its system dependencies: ${missingSystemDependencies}`);log.warn(`Finish with: ${cyan(`cd ${name??"."} && pantry install`)}`);log.warn(`Its JavaScript packages were installed with ${cyan("bun install")} instead, so everything else is ready.`);await log.flush();process.exit(ExitCode.FatalError)}if(startTime){const time=performance.now()-startTime;log.success(dim(`[${time.toFixed(2)}ms] Completed`))}log.info(bold("Welcome to the Stacks Framework! \u269B\uFE0F"));log.info(`Get started: ${cyan(`cd ${name}`)} and then ${cyan("./buddy dev")}`);log.info(`Run ${cyan("./buddy doctor")} anytime to check your setup`);log.info("To learn more, visit https://stacksjs.com");await log.flush();process.exit(ExitCode.Success)});onUnknownSubcommand(buddy,"new")}export function scaffoldTargetOccupants(path){if(!isFolder(path))return[];return readdirSync(path).filter((entry)=>entry!==".git")}function isFolderCheck(path){if(scaffoldTargetOccupants(path).length===0)return;console.error(`Path ${path} already exists`);process.exit(ExitCode.FatalError)}async function onlineCheck(){const offline=await offlineReason();if(!offline)return;log.info(`It appears you are disconnected from the internet (github.com: ${offline}).`);log.info("Creating a new project requires a brief internet connection to download the template and install dependencies.");await log.flush();process.exit(ExitCode.FatalError)}export async function offlineReason(fetcher=fetch){try{await fetcher("https://github.com",{method:"HEAD",signal:AbortSignal.timeout(3000)});return null}catch(error){return error instanceof Error?error.message:String(error)}}export async function templateRef(fetchVersions=fetchPublishedVersions){try{const{latest}=await fetchVersions("stacks");return latest?`v${latest}`:null}catch{return null}}export function templateSpec(ref){return ref?`gh:stacksjs/stacks#${ref}`:"gh:stacksjs/stacks"}async function download(name,path,_options){log.info("Setting up your stack.");const ref=await templateRef();try{const{downloadTemplate}=await import("@stacksjs/gitit");try{await downloadTemplate(templateSpec(ref),{dir:name,force:!0})}catch(error){if(!ref)throw error;log.warn(`No ${ref} tag to scaffold from (${error instanceof Error?error.message:String(error)}).`);log.info("Falling back to the default branch. If this app does not typecheck, that gap is why.");await downloadTemplate(templateSpec(null),{dir:name,force:!0})}log.success(`Successfully scaffolded your project at ${cyan(path)}`);return{isErr:!1}}catch(error){return{isErr:!0,error:error instanceof Error?error.message:String(error)}}}function applyAppVcsTemplate(path){const source=resolve(path,"storage/framework/defaults/vcs/github"),destination=resolve(path,".github");if(!existsSync(source)){log.warn("No app CI template found at storage/framework/defaults/vcs/github - leaving .github as downloaded.");return}log.info("Installing app-shaped GitHub workflows...");try{rmSync(destination,{recursive:!0,force:!0});cpSync(source,destination,{recursive:!0});log.success("App CI installed")}catch(error){log.warn(`Could not install the app CI template: ${error instanceof Error?error.message:String(error)}`)}}function applyAppConfigTemplate(path){const source=resolve(path,"storage/framework/defaults/scaffold/config"),destination=resolve(path,"config");if(!existsSync(source)){log.warn("No app config template found at storage/framework/defaults/scaffold/config - leaving config as downloaded.");return}const identity=appIdentity(path);log.info("Installing app-safe infrastructure configuration...");try{for(const file of readdirSync(source)){if(!file.endsWith(".ts"))continue;const template=readFileSync(resolve(source,file),"utf8");writeFileSync(resolve(destination,file),renderTemplate(template,identity))}log.success("App-safe infrastructure configuration installed")}catch(error){log.warn(`Could not install the app config template: ${error instanceof Error?error.message:String(error)}`)}}function applyAppEnv(path){try{const changed=applyAppEnvTemplate(path,appIdentity(path));if(changed.length>0)log.success(`Named the app in .env.example (${changed.join(", ")})`)}catch(error){log.warn(`Could not name the app in .env.example: ${error instanceof Error?error.message:String(error)}`)}}function applyAppPackage(path){try{const identity=appIdentity(path),changed=applyAppPackageTemplate(path,identity);if(changed.length>0)log.success(`Named the app in package.json (${changed.join(", ")})`);if(applyAppChangelogTemplate(path,identity))log.success("Started the app its own CHANGELOG.md");if(removeFrameworkLicense(path))log.success("Removed the framework's LICENSE.md - choose the app's own licence")}catch(error){log.warn(`Could not name the app in package.json: ${error instanceof Error?error.message:String(error)}`)}}function applyAppAgents(path){try{if(applyAppAgentsTemplate(path))log.success("AGENTS.md no longer tells agents to publish as the framework's author")}catch(error){log.warn(`Could not update AGENTS.md: ${error instanceof Error?error.message:String(error)}`)}}function applyAppReadme(path){const source=resolve(path,"storage/framework/defaults/scaffold/README.md");if(!existsSync(source))return;try{writeFileSync(resolve(path,"README.md"),renderTemplate(readFileSync(source,"utf8"),appIdentity(path)))}catch(error){log.warn(`Could not write the app README: ${error instanceof Error?error.message:String(error)}`)}}function replaceFrameworkSite(path){log.info("Replacing the stacksjs.com site with a starter page...");try{const removed=applyAppSiteTemplate(path);log.success(`Starter page installed (${removed.length} stacksjs.com path${removed.length===1?"":"s"} removed)`)}catch(error){log.warn(`Could not install the starter page: ${error instanceof Error?error.message:String(error)}`)}}function removeFrameworkTests(path){const tests=resolve(path,"tests");if(!existsSync(tests))return;log.info("Removing the framework's own test suite...");for(const entry of readdirSync(tests)){if(entry==="setup.ts")continue;rmSync(resolve(tests,entry),{recursive:!0,force:!0})}log.success("App starts with a clean test suite")}function ensureExecutableScripts(path){for(const script of["buddy","bootstrap"])try{chmodSync(resolve(path,script),493)}catch{}}async function ensureEnv(path,options){log.info("Ensuring your environment is ready...");if(options.provision===!1){const installed=await runCommand(["bun","install"],{cwd:path});if(resultFailed(installed))throw installed.error;log.success("JavaScript dependencies installed; system provisioning skipped");return null}const outcome=await installScaffoldDependencies({pantry:async()=>{const failure=await attemptPantryDependencies(path);return failure===null?null:failureReason(failure.error)},hasNodeModules:()=>existsSync(resolve(path,"node_modules")),bunInstall:async()=>{const bun=bunExecutable(Bun.which("bun"),process.execPath,isCompiledBinary());if(bun===null)return"Bun is not on PATH, and this buddy is a compiled binary, so it cannot run Bun itself.";log.info("Installing the JavaScript packages with Bun...");const result=await runCommand([bun,"install"],{cwd:path});return resultFailed(result)?failureReason(result.error):null}});if(outcome.status==="complete"){log.success("Environment is ready");return null}if(outcome.status==="system-dependencies-missing"){log.warn(`Pantry could not install the system dependencies (${outcome.pantryFailure}). Continuing with the JavaScript packages Bun installed.`);return outcome.pantryFailure}if(outcome.pantryFailure!==null)await log.error(`Pantry could not install the dependencies: ${outcome.pantryFailure}`);await log.error(`Bun could not install the JavaScript packages either: ${outcome.bunFailure}`);await log.error(`${path} is only partly scaffolded. Delete it and run \`buddy new\` again once the installers can reach their registries.`);process.exit(ExitCode.FatalError)}async function install(path,options){log.info("Installing & setting up Stacks");log.info("Copying .env.example \u2192 .env");let result=await runCommand("cp .env.example .env",{...options,cwd:path});if(resultFailed(result)){await log.error(result.error);process.exit(ExitCode.FatalError)}log.info("Removing template-encrypted env files...");const{rm}=await import("node:fs/promises");for(const stale of[".env.development",".env.staging",".env.production",".env.keys"])await rm(`${path}/${stale}`,{force:!0});log.info("Generating application key...");const keyResult=await runAction(Action.KeyGenerate,{...options,cwd:path});if(resultFailed(keyResult)){await log.error(keyResult.error);process.exit(ExitCode.FatalError)}if(existsSync(resolve(path,".git")))log.info("Existing git repository detected, skipping git init");else{log.info("Initializing git repository...");result=await runCommand("git init",{...options,cwd:path});if(resultFailed(result)){await log.error(result.error);process.exit(ExitCode.FatalError)}}log.success("Installed & set-up \uD83D\uDE80")}async function unvendorCore(path,options,withBun){log.info("Resolving the framework from npm (pass --with-core to keep it vendored)...");const result=await runCommand(withBun?"./buddy unpublish:core --all --force --installer bun":"./buddy unpublish:core --all --force",{...options,cwd:path});if(resultFailed(result)){const reason=result.error instanceof Error?result.error.stack??result.error.message:String(result.error??"").trim();log.error("Could not resolve the framework from npm.");log.error(reason.length>0?reason:"The step failed without reporting a reason.");log.error("");log.error(`The project at ${path} is half converted: the vendored framework has been`);log.error("removed and the published packages are not in place yet, so ./buddy cannot");log.error("boot there. Finish it by hand with:");log.error("");await log.error(` cd ${path} && rm -f node_modules/stacks && bun install`);await log.error("");await log.error("Or start over with `--with-core` to keep the framework vendored.");process.exit(ExitCode.FatalError)}log.success("Framework resolved from npm")}async function generatePantryDeps(path){try{if(await optimizePantryDeps(path))rmSync(resolve(path,"deps.yml"),{force:!0})}catch(error){log.warn(`Could not generate deps.yaml from config/deps.ts, keeping the template's deps.yml: ${error instanceof Error?error.message:String(error)}`)}}function trimFrameworkOnlyFiles(path){try{const removed=pruneFrameworkOnlyFiles(path),scripts=applyAppPackageScripts(path);rewriteCoreContentPaths(path);stripFrameworkManifestCredits(path);log.success(`Removed ${removed.length} framework-only path${removed.length===1?"":"s"} and ${scripts.removed.length} framework-only script${scripts.removed.length===1?"":"s"}`)}catch(error){log.warn(`Could not remove the framework-only files: ${error instanceof Error?error.message:String(error)}`)}}function linkFrameworkDefaults(path){log.info("Linking the framework defaults from node_modules (pass --vendor-defaults to commit a copy)...");try{const adopted=adoptPackagedDefaults(path);log.success(`storage/framework/defaults now links to ${relative(path,adopted.packageRoot)}`)}catch(error){log.warn(`Could not move the framework defaults to node_modules: ${error instanceof Error?error.message:String(error)}`)}}async function regenerateAutoImports(path,options){const result=await runCommand("./buddy generate --types",{...options,cwd:path});if(resultFailed(result))log.warn("Could not regenerate the auto-import barrels. Run `./buddy generate --types` in the project before `./buddy dev`.")}async function stripFeatures(path){log.info("Stripping optional feature bundles (--minimal)...");const results=await uninstallAllFeatures({root:path}),authEnv=ensureAuthRoutesEnv(path);if(authEnv.length>0)log.info(` - kept the auth routes mounted (STACKS_DEFAULT_ROUTES=auth in ${authEnv.join(", ")})`);let strippedAny=!1;for(const{feature,configOutcome,filesRemoved}of results)if(configOutcome==="flipped"||filesRemoved.length>0){strippedAny=!0;const fileSummary=filesRemoved.length>0?` (${filesRemoved.length} path${filesRemoved.length===1?"":"s"})`:"";log.info(` - ${feature}${fileSummary}`)}if(!strippedAny)log.info(" \u2192 no feature scaffolding present; nothing to strip.");else log.success("Minimal skeleton ready - run `./buddy <feature>:install` to add features back.")}
@@ -1,10 +1,10 @@
1
- import{existsSync,lstatSync,mkdirSync,realpathSync,unlinkSync}from"node:fs";import{cp,readdir,stat}from"node:fs/promises";import{homedir}from"node:os";import{dirname,join,resolve}from"node:path";import process from"node:process";import{italic,log,onUnknownSubcommand}from"@stacksjs/cli";import{syncPackageProjectFiles,vendorDefaultsTree}from"@stacksjs/actions/upgrade/package-project";import{installedDefaultsVersion,linkPackagedDefaults,packagedDefaultsRoot,path,usesVendoredDefaults}from"@stacksjs/path";import{fs,globSync}from"@stacksjs/storage";import{pruneVendoredCoreFromWorkflows,splitFrameworkTypecheckScript}from"../workflow-prune";import{detectInstaller,findCoreReferences,INSTALL_RETRY_DELAYS_MS,installWithRetry,isDanglingLink,rewriteCoreCommandPaths,rewriteCoreSourceImports,rewriteSurvivingFrameworkManifests}from"../unvendor-rewrite";import{fetchPublishedVersions}from"../registry";import{locateDefaultStx,pointImportsAtDefaults}from"../publish-stx";import{adoptPackagedDefaults,unignoreDefaults,VENDORED_DEFAULTS}from"../scaffold-package-app";import{ExitCode}from"@stacksjs/types";export function publish(buddy){const descriptions={command:"Publish a Stacks default into your userland (app/) directory so you can customize it",model:"Publish a default model from storage/framework/defaults/app/Models/ to app/Models/",controller:"Publish a default controller from storage/framework/defaults/app/Controllers/ to app/Controllers/",middleware:"Publish a default middleware from storage/framework/defaults/app/Middleware/ to app/Middleware/",action:"Publish a default action from storage/framework/defaults/app/Actions/ to app/Actions/",component:"Publish a default component to the same path under resources/components/, by name or by its path there",view:"Publish a default view to resources/views/<path>, e.g. dashboard/commerce/orders or login",core:"Publish a framework package source from node_modules/@stacksjs/<pkg>/ into storage/framework/core/<pkg>/ for editing",unpublishCore:"Drop a vendored storage/framework/core/<pkg>/ and go back to the installed @stacksjs/<pkg>",all:"Unvendor the whole framework: remove storage/framework/core and resolve every @stacksjs package from the `stacks` dependency in package.json",publishAll:"Vendor the whole framework: copy storage/framework/core out of a local Stacks checkout and wire it up as a Bun workspace",frameworkPath:"The Stacks checkout to vendor from (defaults to $STACKS_FRAMEWORK_PATH, ../stacks, then ~/Code/stacks)",coreStatus:"Report whether this project runs on a vendored storage/framework/core or on the published packages",publishDefaults:"Commit a copy of the framework defaults in storage/framework/defaults instead of linking it to node_modules/@stacksjs/defaults",unpublishDefaults:"Drop the vendored storage/framework/defaults and run the installed @stacksjs/defaults through a gitignored link",forceDefaults:"Drop the vendored tree even where it differs from the installed package",name:"The name of the resource to publish (e.g. Cart, User)",pkg:"The name of the framework package (e.g. router, orm, faker - without @stacksjs/ prefix)",force:"Overwrite an existing userland file",forceUnpublish:"Delete the vendored source even when it has uncommitted changes",verbose:"Enable verbose output"};buddy.command("publish:model <name>",descriptions.model).option("--force",descriptions.force,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(name,options)=>{await publishResource({kind:"model",name,defaultsDir:path.frameworkPath("defaults/app/Models"),userDir:path.userModelsPath(),force:!!options.force})});buddy.command("publish:controller <name>",descriptions.controller).option("--force",descriptions.force,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(name,options)=>{await publishResource({kind:"controller",name,defaultsDir:path.frameworkPath("defaults/app/Controllers"),userDir:path.userControllersPath(),force:!!options.force})});buddy.command("publish:middleware <name>",descriptions.middleware).option("--force",descriptions.force,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(name,options)=>{await publishResource({kind:"middleware",name,defaultsDir:path.frameworkPath("defaults/app/Middleware"),userDir:path.userMiddlewarePath(),force:!!options.force})});buddy.command("publish:action <name>",descriptions.action).option("--force",descriptions.force,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(name,options)=>{await publishResource({kind:"action",name,defaultsDir:path.frameworkPath("defaults/app/Actions"),userDir:path.userActionsPath(),force:!!options.force})});buddy.command("publish:component <name>",descriptions.component).option("--force",descriptions.force,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).example("buddy publish:component Pagination").example("buddy publish:component Storefront/ProductCard").action(async(name,options)=>{await publishStx("component",name,!!options.force)});buddy.command("publish:view <path>",descriptions.view).option("--force",descriptions.force,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).example("buddy publish:view login").example("buddy publish:view dashboard/commerce/orders").action(async(name,options)=>{await publishStx("view",name,!!options.force)});buddy.command("publish:core [pkg]",descriptions.core).option("--all",descriptions.publishAll,{default:!1}).option("--path <path>",descriptions.frameworkPath).option("--force",descriptions.force,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).example("buddy publish:core router").example("buddy publish:core --all").example("buddy publish:core --all --path ../stacks").action(async(pkg,options)=>{if(options.all){await vendorFramework(options.path,!!options.force);return}if(!pkg){await log.error("Usage: buddy publish:core <pkg> (or --all to vendor the whole framework as a workspace)");process.exit(ExitCode.FatalError)}await publishCorePackage(pkg,!!options.force)});buddy.command("core:status",descriptions.coreStatus).alias("publish:core:status").option("--verbose",descriptions.verbose,{default:!1}).example("buddy core:status").action(async()=>{await reportCoreStatus()});buddy.command("unpublish:core [pkg]",descriptions.unpublishCore).option("--all",descriptions.all,{default:!1}).option("--force",descriptions.forceUnpublish,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(pkg,options)=>{if(options.all){await unvendorFramework(!!options.force);return}if(!pkg){await log.error("Usage: buddy unpublish:core <pkg> (or --all to move the whole framework to node_modules)");process.exit(ExitCode.FatalError)}await unpublishCorePackage(pkg,!!options.force)});buddy.command("publish:defaults",descriptions.publishDefaults).option("--verbose",descriptions.verbose,{default:!1}).example("buddy publish:defaults").action(async()=>{await vendorDefaults()});buddy.command("unpublish:defaults",descriptions.unpublishDefaults).option("--force",descriptions.forceDefaults,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).example("buddy unpublish:defaults").action(async(options)=>{await unvendorDefaults(!!options.force)});buddy.command("publish [resource] [name]",descriptions.command).option("--force",descriptions.force,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(resource,name,options)=>{if(!resource||!name){await log.error("Usage: buddy publish:<resource> <Name> (e.g. buddy publish:model Cart)");process.exit(ExitCode.FatalError)}const handler={model:()=>publishResource({kind:"model",name,defaultsDir:path.frameworkPath("defaults/app/Models"),userDir:path.userModelsPath(),force:!!options.force}),controller:()=>publishResource({kind:"controller",name,defaultsDir:path.frameworkPath("defaults/app/Controllers"),userDir:path.userControllersPath(),force:!!options.force}),middleware:()=>publishResource({kind:"middleware",name,defaultsDir:path.frameworkPath("defaults/app/Middleware"),userDir:path.userMiddlewarePath(),force:!!options.force}),action:()=>publishResource({kind:"action",name,defaultsDir:path.frameworkPath("defaults/app/Actions"),userDir:path.userActionsPath(),force:!!options.force}),component:()=>publishStx("component",name,!!options.force),view:()=>publishStx("view",name,!!options.force),core:()=>publishCorePackage(name,!!options.force)}[resource.toLowerCase()];if(!handler){await log.error(`Unknown publishable resource: ${italic(resource)}`);log.info("Available: model, controller, middleware, action, component, view, core");await log.flush();process.exit(ExitCode.FatalError)}await handler()});onUnknownSubcommand(buddy,"publish")}async function publishCorePackage(pkg,force){const shortName=pkg.replace(/^@stacksjs\//,"").replace(/^core\//,""),fail=(msg,hint)=>{process.stderr.write(`${msg}
1
+ import{existsSync,lstatSync,mkdirSync,realpathSync,unlinkSync}from"node:fs";import{cp,readdir,stat}from"node:fs/promises";import{homedir}from"node:os";import{dirname,join,resolve}from"node:path";import process from"node:process";import{italic,log,onUnknownSubcommand}from"@stacksjs/cli";import{syncPackageProjectFiles,vendorDefaultsTree}from"@stacksjs/actions/upgrade/package-project";import{installedDefaultsVersion,linkPackagedDefaults,packagedDefaultsRoot,path,usesVendoredDefaults}from"@stacksjs/path";import{fs,globSync}from"@stacksjs/storage";import{pruneVendoredCoreFromWorkflows,splitFrameworkTypecheckScript}from"../workflow-prune";import{chooseInstaller,findCoreReferences,INSTALL_RETRY_DELAYS_MS,installWithRetry,isDanglingLink,isUnvendorInstaller,rewriteCoreCommandPaths,rewriteCoreSourceImports,rewriteSurvivingFrameworkManifests,UNVENDOR_INSTALLERS}from"../unvendor-rewrite";import{fetchPublishedVersions}from"../registry";import{locateDefaultStx,pointImportsAtDefaults}from"../publish-stx";import{adoptPackagedDefaults,unignoreDefaults,VENDORED_DEFAULTS}from"../scaffold-package-app";import{ExitCode}from"@stacksjs/types";export function publish(buddy){const descriptions={command:"Publish a Stacks default into your userland (app/) directory so you can customize it",model:"Publish a default model from storage/framework/defaults/app/Models/ to app/Models/",controller:"Publish a default controller from storage/framework/defaults/app/Controllers/ to app/Controllers/",middleware:"Publish a default middleware from storage/framework/defaults/app/Middleware/ to app/Middleware/",action:"Publish a default action from storage/framework/defaults/app/Actions/ to app/Actions/",component:"Publish a default component to the same path under resources/components/, by name or by its path there",view:"Publish a default view to resources/views/<path>, e.g. dashboard/commerce/orders or login",core:"Publish a framework package source from node_modules/@stacksjs/<pkg>/ into storage/framework/core/<pkg>/ for editing",unpublishCore:"Drop a vendored storage/framework/core/<pkg>/ and go back to the installed @stacksjs/<pkg>",all:"Unvendor the whole framework: remove storage/framework/core and resolve every @stacksjs package from the `stacks` dependency in package.json",publishAll:"Vendor the whole framework: copy storage/framework/core out of a local Stacks checkout and wire it up as a Bun workspace",frameworkPath:"The Stacks checkout to vendor from (defaults to $STACKS_FRAMEWORK_PATH, ../stacks, then ~/Code/stacks)",coreStatus:"Report whether this project runs on a vendored storage/framework/core or on the published packages",publishDefaults:"Commit a copy of the framework defaults in storage/framework/defaults instead of linking it to node_modules/@stacksjs/defaults",unpublishDefaults:"Drop the vendored storage/framework/defaults and run the installed @stacksjs/defaults through a gitignored link",forceDefaults:"Drop the vendored tree even where it differs from the installed package",name:"The name of the resource to publish (e.g. Cart, User)",pkg:"The name of the framework package (e.g. router, orm, faker - without @stacksjs/ prefix)",force:"Overwrite an existing userland file",forceUnpublish:"Delete the vendored source even when it has uncommitted changes",installer:"Install the published packages with `bun` or `pantry` instead of detecting which one the project uses",verbose:"Enable verbose output"};buddy.command("publish:model <name>",descriptions.model).option("--force",descriptions.force,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(name,options)=>{await publishResource({kind:"model",name,defaultsDir:path.frameworkPath("defaults/app/Models"),userDir:path.userModelsPath(),force:!!options.force})});buddy.command("publish:controller <name>",descriptions.controller).option("--force",descriptions.force,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(name,options)=>{await publishResource({kind:"controller",name,defaultsDir:path.frameworkPath("defaults/app/Controllers"),userDir:path.userControllersPath(),force:!!options.force})});buddy.command("publish:middleware <name>",descriptions.middleware).option("--force",descriptions.force,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(name,options)=>{await publishResource({kind:"middleware",name,defaultsDir:path.frameworkPath("defaults/app/Middleware"),userDir:path.userMiddlewarePath(),force:!!options.force})});buddy.command("publish:action <name>",descriptions.action).option("--force",descriptions.force,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(name,options)=>{await publishResource({kind:"action",name,defaultsDir:path.frameworkPath("defaults/app/Actions"),userDir:path.userActionsPath(),force:!!options.force})});buddy.command("publish:component <name>",descriptions.component).option("--force",descriptions.force,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).example("buddy publish:component Pagination").example("buddy publish:component Storefront/ProductCard").action(async(name,options)=>{await publishStx("component",name,!!options.force)});buddy.command("publish:view <path>",descriptions.view).option("--force",descriptions.force,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).example("buddy publish:view login").example("buddy publish:view dashboard/commerce/orders").action(async(name,options)=>{await publishStx("view",name,!!options.force)});buddy.command("publish:core [pkg]",descriptions.core).option("--all",descriptions.publishAll,{default:!1}).option("--path <path>",descriptions.frameworkPath).option("--force",descriptions.force,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).example("buddy publish:core router").example("buddy publish:core --all").example("buddy publish:core --all --path ../stacks").action(async(pkg,options)=>{if(options.all){await vendorFramework(options.path,!!options.force);return}if(!pkg){await log.error("Usage: buddy publish:core <pkg> (or --all to vendor the whole framework as a workspace)");process.exit(ExitCode.FatalError)}await publishCorePackage(pkg,!!options.force)});buddy.command("core:status",descriptions.coreStatus).alias("publish:core:status").option("--verbose",descriptions.verbose,{default:!1}).example("buddy core:status").action(async()=>{await reportCoreStatus()});buddy.command("unpublish:core [pkg]",descriptions.unpublishCore).option("--all",descriptions.all,{default:!1}).option("--force",descriptions.forceUnpublish,{default:!1}).option("--installer <installer>",descriptions.installer).option("--verbose",descriptions.verbose,{default:!1}).action(async(pkg,options)=>{if(options.installer!==void 0&&!isUnvendorInstaller(options.installer)){await log.error(`--installer must be one of ${UNVENDOR_INSTALLERS.join(", ")}, not "${String(options.installer)}".`);process.exit(ExitCode.InvalidArgument)}if(options.all){await unvendorFramework(!!options.force,options.installer);return}if(!pkg){await log.error("Usage: buddy unpublish:core <pkg> (or --all to move the whole framework to node_modules)");process.exit(ExitCode.FatalError)}await unpublishCorePackage(pkg,!!options.force)});buddy.command("publish:defaults",descriptions.publishDefaults).option("--verbose",descriptions.verbose,{default:!1}).example("buddy publish:defaults").action(async()=>{await vendorDefaults()});buddy.command("unpublish:defaults",descriptions.unpublishDefaults).option("--force",descriptions.forceDefaults,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).example("buddy unpublish:defaults").action(async(options)=>{await unvendorDefaults(!!options.force)});buddy.command("publish [resource] [name]",descriptions.command).option("--force",descriptions.force,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(resource,name,options)=>{if(!resource||!name){await log.error("Usage: buddy publish:<resource> <Name> (e.g. buddy publish:model Cart)");process.exit(ExitCode.FatalError)}const handler={model:()=>publishResource({kind:"model",name,defaultsDir:path.frameworkPath("defaults/app/Models"),userDir:path.userModelsPath(),force:!!options.force}),controller:()=>publishResource({kind:"controller",name,defaultsDir:path.frameworkPath("defaults/app/Controllers"),userDir:path.userControllersPath(),force:!!options.force}),middleware:()=>publishResource({kind:"middleware",name,defaultsDir:path.frameworkPath("defaults/app/Middleware"),userDir:path.userMiddlewarePath(),force:!!options.force}),action:()=>publishResource({kind:"action",name,defaultsDir:path.frameworkPath("defaults/app/Actions"),userDir:path.userActionsPath(),force:!!options.force}),component:()=>publishStx("component",name,!!options.force),view:()=>publishStx("view",name,!!options.force),core:()=>publishCorePackage(name,!!options.force)}[resource.toLowerCase()];if(!handler){await log.error(`Unknown publishable resource: ${italic(resource)}`);log.info("Available: model, controller, middleware, action, component, view, core");await log.flush();process.exit(ExitCode.FatalError)}await handler()});onUnknownSubcommand(buddy,"publish")}async function publishCorePackage(pkg,force){const shortName=pkg.replace(/^@stacksjs\//,"").replace(/^core\//,""),fail=(msg,hint)=>{process.stderr.write(`${msg}
2
2
  `);if(hint)process.stderr.write(` ${hint}
3
3
  `);process.exit(ExitCode.FatalError)};if(!shortName||shortName.includes("/")||shortName.includes(".."))fail(`Invalid package name: ${pkg}`,"Use a short name like `router` or the fully qualified `@stacksjs/router`.");const sourceDir=resolve(process.cwd(),"node_modules","@stacksjs",shortName),targetDir=path.frameworkPath(`core/${shortName}`);try{if(!(await stat(sourceDir)).isDirectory())fail(`${sourceDir} is not a directory.`)}catch{fail(`Could not find @stacksjs/${shortName} in node_modules.`,"Run `bun install` first, or check the package name.")}if(existsSync(targetDir)&&!force)fail(`Already published: ${targetDir.replace(`${process.cwd()}/`,"")}`,"Pass --force to overwrite.");mkdirSync(dirname(targetDir),{recursive:!0});const SKIP=new Set(["node_modules","dist",".bun",".cache","tsconfig.tsbuildinfo"]);let copied=0;await copyTreeFiltered(sourceDir,targetDir,SKIP,()=>copied++);log.success(`Published @stacksjs/${shortName} \u2192 ${italic(targetDir.replace(`${process.cwd()}/`,""))} (${copied} files)`);log.info("Edit freely - local changes win over the installed package.")}async function copyTreeFiltered(sourceDir,targetDir,skip,onFile){mkdirSync(targetDir,{recursive:!0});const entries=await readdir(sourceDir,{withFileTypes:!0});for(const entry of entries){if(skip.has(entry.name))continue;const src=`${sourceDir}/${entry.name}`,dst=`${targetDir}/${entry.name}`;if(entry.isDirectory()){await copyTreeFiltered(src,dst,skip,onFile);continue}await cp(src,dst,{force:!0,dereference:!0});onFile()}}async function publishResource(ctx){const{kind,name,defaultsDir,userDir,force}=ctx,fileName=name.endsWith(".ts")?name:`${name}.ts`,matches=globSync([`${defaultsDir}/**/${fileName}`],{absolute:!0});if(!matches.length){await log.error(`Could not find default ${kind}: ${italic(fileName)}`);log.info(`Looked under: ${italic(defaultsDir)}`);await log.flush();process.exit(ExitCode.FatalError)}if(matches.length>1){log.warn(`Multiple defaults match ${italic(fileName)}; using the first:`);for(const m of matches)log.info(` ${m}`)}const sourcePath=matches[0];if(!sourcePath)throw Error(`Could not resolve default ${kind}: ${fileName}`);const targetPath=`${userDir.replace(/\/$/,"")}/${fileName}`;if(existsSync(targetPath)&&!force){await log.error(`Already exists: ${italic(targetPath)}`);log.info("Pass --force to overwrite.");await log.flush();process.exit(ExitCode.FatalError)}mkdirSync(dirname(targetPath),{recursive:!0});await fs.promises.copyFile(sourcePath,targetPath);const carried=await carryRelativeImports(sourcePath,targetPath);log.success(`Published ${kind} ${italic(name)} \u2192 ${italic(targetPath.replace(`${process.cwd()}/`,""))}`);for(const file of carried)log.info(` + ${italic(file.replace(`${process.cwd()}/`,""))} (imported by it)`)}async function publishStx(kind,name,force){const root=path.projectPath(),defaultsRoot=path.frameworkPath("defaults"),found=locateDefaultStx(kind,name,defaultsRoot,root);if(!found.ok){await log.error(found.message);for(const line of found.details)log.info(` ${line}`);await log.flush();process.exit(ExitCode.FatalError)}if(existsSync(found.target)&&!force){await log.error(`Already exists: ${italic(found.target.replace(`${root}/`,""))}`);log.info("Pass --force to overwrite.");await log.flush();process.exit(ExitCode.FatalError)}const source=await fs.promises.readFile(found.source,"utf-8"),{code,rewritten}=pointImportsAtDefaults(source,found.source,defaultsRoot);mkdirSync(dirname(found.target),{recursive:!0});await fs.promises.writeFile(found.target,code);log.success(`Published ${kind} ${italic(name)} \u2192 ${italic(found.target.replace(`${root}/`,""))}`);if(rewritten>0)log.info(` ${rewritten} import${rewritten===1?"":"s"} of the framework's own files now read from @stacksjs/defaults`)}export async function carryRelativeImports(sourcePath,targetPath,seen=new Set){if(seen.has(sourcePath))return[];seen.add(sourcePath);const source=await fs.promises.readFile(sourcePath,"utf-8"),written=[],root=realpathSync(process.cwd()),targetDir=realpathSync(dirname(targetPath)),specifiers=[...source.matchAll(/from\s+['"](\.[^'"]+)['"]/g)].map((match)=>match[1]);for(const specifier of new Set(specifiers)){if(!specifier)continue;const candidates=specifier.endsWith(".ts")?[specifier]:[`${specifier}.ts`,`${specifier}/index.ts`];for(const candidate of candidates){const from=resolve(dirname(sourcePath),candidate),to=resolve(targetDir,candidate);if(!existsSync(from))continue;if(!to.startsWith(`${root}/`))break;if(!existsSync(to)){mkdirSync(dirname(to),{recursive:!0});await fs.promises.copyFile(from,to);written.push(to)}written.push(...await carryRelativeImports(from,to,seen));break}}return written}async function vendorFramework(explicitPath,force){const coreDir=path.frameworkPath("core"),rel=(p)=>p.replace(`${process.cwd()}/`,"");if(existsSync(coreDir)&&!force){log.info(`Already vendored: ${italic(rel(coreDir))}`);log.info("Pass --force to replace it with a fresh copy of the checkout.");return}const framework=resolveFrameworkCheckout(explicitPath);if(!framework){await log.error("No Stacks checkout found to vendor from.");log.info("Pass one with `--path <dir>`, or set STACKS_FRAMEWORK_PATH.");log.info("A checkout is required: the published packages ship `dist` only, so a copy of them would not be editable.");await log.flush();process.exit(ExitCode.FatalError)}const sourceCore=join(framework,"storage/framework/core"),corePkgPath=resolve(sourceCore,"package.json");if(!existsSync(corePkgPath)){await log.error(`${sourceCore} has no package.json - that does not look like a Stacks checkout.`);process.exit(ExitCode.FatalError)}const depName=JSON.parse(await fs.promises.readFile(corePkgPath,"utf-8")).name??"stacks";log.info(`Vendoring the framework from ${italic(framework)}...`);if(existsSync(coreDir))await fs.promises.rm(coreDir,{recursive:!0,force:!0});const SKIP=new Set(["node_modules",".bun",".cache","tsconfig.tsbuildinfo"]);let copied=0;await copyTreeFiltered(sourceCore,coreDir,SKIP,()=>copied++);const rootPkgPath=resolve(process.cwd(),"package.json"),rootPkg=JSON.parse(await fs.promises.readFile(rootPkgPath,"utf-8")),provided=new Set([depName]);for(const entry of await readdir(coreDir,{withFileTypes:!0})){if(!entry.isDirectory())continue;if(existsSync(resolve(coreDir,entry.name,"package.json")))provided.add(`@stacksjs/${entry.name}`)}let repointed=0;for(const field of["dependencies","devDependencies"]){const deps=rootPkg[field];if(!deps)continue;for(const name of Object.keys(deps)){if(!provided.has(name)||deps[name].startsWith("workspace:"))continue;deps[name]="workspace:*";repointed++}}if(!rootPkg.dependencies?.[depName]&&!rootPkg.devDependencies?.[depName])rootPkg.dependencies={...rootPkg.dependencies,[depName]:"workspace:*"};const workspaces=rootPkg.workspaces??[];let addedGlobs=0;for(const glob of["storage/framework/core","storage/framework/core/*"]){if(workspaces.some((existing)=>existing.replace(/^\.\//,"").replace(/\/$/,"")===glob))continue;workspaces.push(glob);addedGlobs++}rootPkg.workspaces=workspaces;await fs.promises.writeFile(rootPkgPath,`${JSON.stringify(rootPkg,null,2)}
4
- `);const bunfigPath=resolve(process.cwd(),"bunfig.toml");let rewrittenPreloads=0;if(existsSync(bunfigPath)){const bunfig=await fs.promises.readFile(bunfigPath,"utf-8"),next=bunfig.replace(/(["'])@stacksjs\/([\w-]+)\/([^"']+?)\.js\1/g,(match,quote,pkgName,subpath)=>{if(!provided.has(`@stacksjs/${pkgName}`))return match;rewrittenPreloads++;return`${quote}./storage/framework/core/${pkgName}/${subpath}.ts${quote}`});if(next!==bunfig)await fs.promises.writeFile(bunfigPath,next)}const tsconfigPath=resolve(process.cwd(),"tsconfig.json");let rewroteTsconfig=!1;if(existsSync(tsconfigPath)){const raw=await fs.promises.readFile(tsconfigPath,"utf-8"),next=raw.replace(/"extends"\s*:\s*"\.\/storage\/framework\/tsconfig\.app\.json"/,'"extends": "./storage/framework/core/tsconfig.json"');if(next!==raw){await fs.promises.writeFile(tsconfigPath,next);rewroteTsconfig=!0}}log.success(`Vendored ${copied} files into ${italic(rel(coreDir))}`);log.info(`package.json now depends on ${depName}@workspace:*`);if(repointed>0)log.info(`Repointed ${repointed} version range${repointed===1?"":"s"} to workspace:*`);if(addedGlobs>0)log.info(`Added ${addedGlobs} workspace glob${addedGlobs===1?"":"s"} for the vendored packages`);if(rewrittenPreloads>0)log.info(`Rewrote ${rewrittenPreloads} bunfig.toml preload path${rewrittenPreloads===1?"":"s"} to the vendored source`);if(rewroteTsconfig)log.info("tsconfig.json now extends storage/framework/core/tsconfig.json");log.info("Linking the workspace...");if(await Bun.spawn(["bun","install"],{cwd:process.cwd(),stdout:"inherit",stderr:"inherit"}).exited!==0){await log.error("`bun install` failed. The files are in place; re-run the install once the failure is resolved.");process.exit(ExitCode.FatalError)}log.success("This project now runs on the vendored framework - edits under storage/framework/core are live.");log.info("Go back to the published packages any time with `buddy unpublish:core --all`.")}function resolveFrameworkCheckout(explicit){const candidates=[explicit,process.env.STACKS_FRAMEWORK_PATH,resolve(process.cwd(),"../stacks"),join(homedir(),"Code/stacks")].filter(Boolean);for(const candidate of candidates){const full=resolve(candidate);if(full===resolve(process.cwd()))continue;if(existsSync(join(full,"storage/framework/core/package.json")))return full}return null}async function reportCoreStatus(){const coreDir=path.frameworkPath("core"),rel=(p)=>p.replace(`${process.cwd()}/`,""),vendored=existsSync(resolve(coreDir,"package.json")),rootPkgPath=resolve(process.cwd(),"package.json"),rootPkg=existsSync(rootPkgPath)?JSON.parse(await fs.promises.readFile(rootPkgPath,"utf-8")):{},declared=rootPkg.dependencies?.stacks??rootPkg.devDependencies?.stacks;if(vendored){const corePkg=JSON.parse(await fs.promises.readFile(resolve(coreDir,"package.json"),"utf-8")),packages=(await readdir(coreDir,{withFileTypes:!0})).filter((entry)=>entry.isDirectory()&&existsSync(resolve(coreDir,entry.name,"package.json")));log.info(`Layout: vendored - ${italic(rel(coreDir))} (${packages.length} packages, v${corePkg.version??"unknown"})`);log.info(`Declared: stacks@${declared??"(not declared)"}`);if(declared&&!declared.startsWith("workspace:"))log.warn(`The vendored copy is not linked: stacks is declared as ${declared}, not workspace:*. Run \`buddy publish:core --all --force\` to relink, or \`buddy unpublish:core --all\` to remove it.`);log.info("Move to the published packages with `buddy unpublish:core --all`.");return}const installed=resolve(process.cwd(),"node_modules/@stacksjs/buddy/package.json"),installedVersion=existsSync(installed)?JSON.parse(await fs.promises.readFile(installed,"utf-8")).version:void 0;log.info("Layout: published packages - no storage/framework/core in this project");log.info(`Declared: stacks@${declared??"(not declared)"}`);log.info(`Installed: ${installedVersion?`v${installedVersion}`:"(run bun install)"}`);log.info("Vendor the framework for local development with `buddy publish:core --all`.")}async function unpublishCorePackage(pkg,force){const shortName=normalizeCoreName(pkg),targetDir=path.frameworkPath(`core/${shortName}`),rel=(p)=>p.replace(`${process.cwd()}/`,"");if(!existsSync(targetDir)){log.info(`Not vendored: ${italic(rel(targetDir))} - nothing to do.`);return}const installed=resolve(process.cwd(),"node_modules","@stacksjs",shortName);if(!existsSync(installed)&&!force){await log.error(`@stacksjs/${shortName} is not installed, so removing the vendored copy would leave nothing to resolve.`);log.info(`Run \`bun add @stacksjs/${shortName}\` first, or pass --force to remove it anyway.`);await log.flush();process.exit(ExitCode.FatalError)}await assertNoUncommittedChanges(targetDir,force);await fs.promises.rm(targetDir,{recursive:!0,force:!0});log.success(`Unpublished ${italic(rel(targetDir))} - @stacksjs/${shortName} now resolves from node_modules.`)}export function packagesPreloadFilesFallBackTo(source){const found=new Set;for(const match of source.matchAll(/'@stacksjs\/'\s*\+\s*'([a-z0-9-]+)'/g))found.add(`@stacksjs/${match[1]}`);return found}export function rewriteBunfigPreloads(bunfig){const packages=new Set;let rewritten=0;return{next:bunfig.replace(/(["'])\.?\/?storage\/framework\/core\/([\w-]+)\/([^"']+?)\.ts\1/g,(_match,quote,pkgName,subpath)=>{rewritten++;packages.add(`@stacksjs/${pkgName}`);return`${quote}@stacksjs/${pkgName}/${subpath}.js${quote}`}),packages,rewritten}}async function vendorDefaults(){const root=path.projectPath();if(usesVendoredDefaults(root)){log.info(`${VENDORED_DEFAULTS} is already a vendored copy.`);return}const packageRoot=packagedDefaultsRoot(root);if(!packageRoot){await log.error("@stacksjs/defaults is not installed, so there is nothing to copy. Install the project's dependencies first.");process.exit(ExitCode.FatalError)}const tree=resolve(root,VENDORED_DEFAULTS);try{if(lstatSync(tree).isSymbolicLink())unlinkSync(tree)}catch{}mkdirSync(tree,{recursive:!0});const changes=vendorDefaultsTree(root,packageRoot);unignoreDefaults(root);log.success(`Copied @stacksjs/defaults ${installedDefaultsVersion(root)??""} into ${VENDORED_DEFAULTS} (${changes.length} files). Commit it; \`buddy upgrade\` keeps it current.`);log.info("Go back to the link any time with `buddy unpublish:defaults`.")}async function unvendorDefaults(force){const root=path.projectPath();if(!usesVendoredDefaults(root)){linkPackagedDefaults(root);log.info(`${VENDORED_DEFAULTS} already runs from node_modules/@stacksjs/defaults.`);return}if(existsSync(resolve(root,"storage/framework/core/buddy/package.json"))){await log.error("This project vendors the framework itself (storage/framework/core), and its defaults tree is the source the package is built from. Run `buddy unpublish:core --all` first.");process.exit(ExitCode.FatalError)}const packageRoot=packagedDefaultsRoot(root);if(!packageRoot){await log.error("@stacksjs/defaults is not installed, so there is nothing to run the defaults from. Install the project's dependencies first.");process.exit(ExitCode.FatalError)}const differs=syncPackageProjectFiles(root,packageRoot,{dryRun:!0,vendorDefaults:!0}).filter((change)=>change.path.startsWith(`${VENDORED_DEFAULTS}/`)&&change.action!=="add");if(differs.length>0&&!force){await log.error(`${VENDORED_DEFAULTS} differs from the installed @stacksjs/defaults ${installedDefaultsVersion(root)??""} in ${differs.length} place${differs.length===1?"":"s"}:`);for(const change of differs.slice(0,15))log.error(` ${change.action==="remove"?"only here":"changed "} ${change.path}`);if(differs.length>15)log.error(` ... and ${differs.length-15} more`);log.info("A tree from another release: run `buddy upgrade` first. A file you edited: move it to the same path under app/, which wins over the defaults. Then run this again, or pass --force to drop the differences.");await log.flush();process.exit(ExitCode.FatalError)}const adopted=adoptPackagedDefaults(root);log.success(`Removed ${VENDORED_DEFAULTS}; it now links to ${adopted.packageRoot.replace(`${root}/`,"")} and is gitignored.`);for(const file of[...adopted.rewrittenImports,...adopted.rewrittenModulePaths])log.info(` repointed ${file} at @stacksjs/defaults`);log.info("Commit the removal. Go back to a vendored copy any time with `buddy publish:defaults`.")}async function unvendorFramework(force){const coreDir=path.frameworkPath("core"),rel=(p)=>p.replace(`${process.cwd()}/`,"");if(!existsSync(coreDir)){log.info("No storage/framework/core in this project - already on the installed packages.");return}const corePkgPath=resolve(coreDir,"package.json");if(!existsSync(corePkgPath)){await log.error(`${rel(coreDir)} has no package.json, so its version cannot be determined.`);log.info("Unvendor the packages individually with `buddy unpublish:core <pkg>` instead.");await log.flush();process.exit(ExitCode.FatalError)}const corePkg=JSON.parse(await fs.promises.readFile(corePkgPath,"utf-8")),version=corePkg.version;if(!version){await log.error(`${rel(corePkgPath)} has no version field.`);process.exit(ExitCode.FatalError)}await assertNoUncommittedChanges(coreDir,force);const depName=corePkg.name??"stacks",range=`^${await resolvePublishedVersion(depName,version)}`,rootPkgPath=resolve(process.cwd(),"package.json"),rootPkgRaw=await fs.promises.readFile(rootPkgPath,"utf-8"),rootPkg=JSON.parse(rootPkgRaw),provided=new Set([depName,...Object.keys(corePkg.dependencies??{}).filter((name)=>name.startsWith("@stacksjs/"))]);for(const entry of await readdir(coreDir,{withFileTypes:!0}))if(entry.isDirectory())provided.add(`@stacksjs/${entry.name}`);let repointed=0;const repointWorkspaceRanges=(pkg)=>{let touched=!1;for(const field of["dependencies","devDependencies","peerDependencies"]){const deps=pkg[field];if(!deps)continue;for(const[name,spec]of Object.entries(deps)){if(!spec.startsWith("workspace:")||!provided.has(name))continue;deps[name]=range;touched=!0;repointed++}}return touched};repointWorkspaceRanges(rootPkg);if(!rootPkg.dependencies?.[depName]&&!rootPkg.devDependencies?.[depName])rootPkg.dependencies={...rootPkg.dependencies,[depName]:range};let rewrittenScripts=0;for(const[name,script]of Object.entries(rootPkg.scripts??{})){if(!/storage\/framework\/core\/buddy\/src\/cli\.ts/.test(script))continue;rootPkg.scripts[name]=script.replace(/\bbunx?\s+(?:--bun\s+)?\.?\/?storage\/framework\/core\/buddy\/src\/cli\.ts/g,"./buddy");rewrittenScripts++}if(Array.isArray(rootPkg.workspaces)){rootPkg.workspaces=rootPkg.workspaces.filter((glob)=>!isCoreWorkspaceGlob(glob));if(rootPkg.workspaces.length===0)delete rootPkg.workspaces}await fs.promises.writeFile(rootPkgPath,`${JSON.stringify(rootPkg,null,2)}
4
+ `);const bunfigPath=resolve(process.cwd(),"bunfig.toml");let rewrittenPreloads=0;if(existsSync(bunfigPath)){const bunfig=await fs.promises.readFile(bunfigPath,"utf-8"),next=bunfig.replace(/(["'])@stacksjs\/([\w-]+)\/([^"']+?)\.js\1/g,(match,quote,pkgName,subpath)=>{if(!provided.has(`@stacksjs/${pkgName}`))return match;rewrittenPreloads++;return`${quote}./storage/framework/core/${pkgName}/${subpath}.ts${quote}`});if(next!==bunfig)await fs.promises.writeFile(bunfigPath,next)}const tsconfigPath=resolve(process.cwd(),"tsconfig.json");let rewroteTsconfig=!1;if(existsSync(tsconfigPath)){const raw=await fs.promises.readFile(tsconfigPath,"utf-8"),next=raw.replace(/"extends"\s*:\s*"\.\/storage\/framework\/tsconfig\.app\.json"/,'"extends": "./storage/framework/core/tsconfig.json"');if(next!==raw){await fs.promises.writeFile(tsconfigPath,next);rewroteTsconfig=!0}}log.success(`Vendored ${copied} files into ${italic(rel(coreDir))}`);log.info(`package.json now depends on ${depName}@workspace:*`);if(repointed>0)log.info(`Repointed ${repointed} version range${repointed===1?"":"s"} to workspace:*`);if(addedGlobs>0)log.info(`Added ${addedGlobs} workspace glob${addedGlobs===1?"":"s"} for the vendored packages`);if(rewrittenPreloads>0)log.info(`Rewrote ${rewrittenPreloads} bunfig.toml preload path${rewrittenPreloads===1?"":"s"} to the vendored source`);if(rewroteTsconfig)log.info("tsconfig.json now extends storage/framework/core/tsconfig.json");log.info("Linking the workspace...");if(await Bun.spawn(["bun","install"],{cwd:process.cwd(),stdout:"inherit",stderr:"inherit"}).exited!==0){await log.error("`bun install` failed. The files are in place; re-run the install once the failure is resolved.");process.exit(ExitCode.FatalError)}log.success("This project now runs on the vendored framework - edits under storage/framework/core are live.");log.info("Go back to the published packages any time with `buddy unpublish:core --all`.")}function resolveFrameworkCheckout(explicit){const candidates=[explicit,process.env.STACKS_FRAMEWORK_PATH,resolve(process.cwd(),"../stacks"),join(homedir(),"Code/stacks")].filter(Boolean);for(const candidate of candidates){const full=resolve(candidate);if(full===resolve(process.cwd()))continue;if(existsSync(join(full,"storage/framework/core/package.json")))return full}return null}async function reportCoreStatus(){const coreDir=path.frameworkPath("core"),rel=(p)=>p.replace(`${process.cwd()}/`,""),vendored=existsSync(resolve(coreDir,"package.json")),rootPkgPath=resolve(process.cwd(),"package.json"),rootPkg=existsSync(rootPkgPath)?JSON.parse(await fs.promises.readFile(rootPkgPath,"utf-8")):{},declared=rootPkg.dependencies?.stacks??rootPkg.devDependencies?.stacks;if(vendored){const corePkg=JSON.parse(await fs.promises.readFile(resolve(coreDir,"package.json"),"utf-8")),packages=(await readdir(coreDir,{withFileTypes:!0})).filter((entry)=>entry.isDirectory()&&existsSync(resolve(coreDir,entry.name,"package.json")));log.info(`Layout: vendored - ${italic(rel(coreDir))} (${packages.length} packages, v${corePkg.version??"unknown"})`);log.info(`Declared: stacks@${declared??"(not declared)"}`);if(declared&&!declared.startsWith("workspace:"))log.warn(`The vendored copy is not linked: stacks is declared as ${declared}, not workspace:*. Run \`buddy publish:core --all --force\` to relink, or \`buddy unpublish:core --all\` to remove it.`);log.info("Move to the published packages with `buddy unpublish:core --all`.");return}const installed=resolve(process.cwd(),"node_modules/@stacksjs/buddy/package.json"),installedVersion=existsSync(installed)?JSON.parse(await fs.promises.readFile(installed,"utf-8")).version:void 0;log.info("Layout: published packages - no storage/framework/core in this project");log.info(`Declared: stacks@${declared??"(not declared)"}`);log.info(`Installed: ${installedVersion?`v${installedVersion}`:"(run bun install)"}`);log.info("Vendor the framework for local development with `buddy publish:core --all`.")}async function unpublishCorePackage(pkg,force){const shortName=normalizeCoreName(pkg),targetDir=path.frameworkPath(`core/${shortName}`),rel=(p)=>p.replace(`${process.cwd()}/`,"");if(!existsSync(targetDir)){log.info(`Not vendored: ${italic(rel(targetDir))} - nothing to do.`);return}const installed=resolve(process.cwd(),"node_modules","@stacksjs",shortName);if(!existsSync(installed)&&!force){await log.error(`@stacksjs/${shortName} is not installed, so removing the vendored copy would leave nothing to resolve.`);log.info(`Run \`bun add @stacksjs/${shortName}\` first, or pass --force to remove it anyway.`);await log.flush();process.exit(ExitCode.FatalError)}await assertNoUncommittedChanges(targetDir,force);await fs.promises.rm(targetDir,{recursive:!0,force:!0});log.success(`Unpublished ${italic(rel(targetDir))} - @stacksjs/${shortName} now resolves from node_modules.`)}export function packagesPreloadFilesFallBackTo(source){const found=new Set;for(const match of source.matchAll(/'@stacksjs\/'\s*\+\s*'([a-z0-9-]+)'/g))found.add(`@stacksjs/${match[1]}`);return found}export function rewriteBunfigPreloads(bunfig){const packages=new Set;let rewritten=0;return{next:bunfig.replace(/(["'])\.?\/?storage\/framework\/core\/([\w-]+)\/([^"']+?)\.ts\1/g,(_match,quote,pkgName,subpath)=>{rewritten++;packages.add(`@stacksjs/${pkgName}`);return`${quote}@stacksjs/${pkgName}/${subpath}.js${quote}`}),packages,rewritten}}async function vendorDefaults(){const root=path.projectPath();if(usesVendoredDefaults(root)){log.info(`${VENDORED_DEFAULTS} is already a vendored copy.`);return}const packageRoot=packagedDefaultsRoot(root);if(!packageRoot){await log.error("@stacksjs/defaults is not installed, so there is nothing to copy. Install the project's dependencies first.");process.exit(ExitCode.FatalError)}const tree=resolve(root,VENDORED_DEFAULTS);try{if(lstatSync(tree).isSymbolicLink())unlinkSync(tree)}catch{}mkdirSync(tree,{recursive:!0});const changes=vendorDefaultsTree(root,packageRoot);unignoreDefaults(root);log.success(`Copied @stacksjs/defaults ${installedDefaultsVersion(root)??""} into ${VENDORED_DEFAULTS} (${changes.length} files). Commit it; \`buddy upgrade\` keeps it current.`);log.info("Go back to the link any time with `buddy unpublish:defaults`.")}async function unvendorDefaults(force){const root=path.projectPath();if(!usesVendoredDefaults(root)){linkPackagedDefaults(root);log.info(`${VENDORED_DEFAULTS} already runs from node_modules/@stacksjs/defaults.`);return}if(existsSync(resolve(root,"storage/framework/core/buddy/package.json"))){await log.error("This project vendors the framework itself (storage/framework/core), and its defaults tree is the source the package is built from. Run `buddy unpublish:core --all` first.");process.exit(ExitCode.FatalError)}const packageRoot=packagedDefaultsRoot(root);if(!packageRoot){await log.error("@stacksjs/defaults is not installed, so there is nothing to run the defaults from. Install the project's dependencies first.");process.exit(ExitCode.FatalError)}const differs=syncPackageProjectFiles(root,packageRoot,{dryRun:!0,vendorDefaults:!0}).filter((change)=>change.path.startsWith(`${VENDORED_DEFAULTS}/`)&&change.action!=="add");if(differs.length>0&&!force){await log.error(`${VENDORED_DEFAULTS} differs from the installed @stacksjs/defaults ${installedDefaultsVersion(root)??""} in ${differs.length} place${differs.length===1?"":"s"}:`);for(const change of differs.slice(0,15))log.error(` ${change.action==="remove"?"only here":"changed "} ${change.path}`);if(differs.length>15)log.error(` ... and ${differs.length-15} more`);log.info("A tree from another release: run `buddy upgrade` first. A file you edited: move it to the same path under app/, which wins over the defaults. Then run this again, or pass --force to drop the differences.");await log.flush();process.exit(ExitCode.FatalError)}const adopted=adoptPackagedDefaults(root);log.success(`Removed ${VENDORED_DEFAULTS}; it now links to ${adopted.packageRoot.replace(`${root}/`,"")} and is gitignored.`);for(const file of[...adopted.rewrittenImports,...adopted.rewrittenModulePaths])log.info(` repointed ${file} at @stacksjs/defaults`);log.info("Commit the removal. Go back to a vendored copy any time with `buddy publish:defaults`.")}async function unvendorFramework(force,requestedInstaller){const coreDir=path.frameworkPath("core"),rel=(p)=>p.replace(`${process.cwd()}/`,"");if(!existsSync(coreDir)){log.info("No storage/framework/core in this project - already on the installed packages.");return}const corePkgPath=resolve(coreDir,"package.json");if(!existsSync(corePkgPath)){await log.error(`${rel(coreDir)} has no package.json, so its version cannot be determined.`);log.info("Unvendor the packages individually with `buddy unpublish:core <pkg>` instead.");await log.flush();process.exit(ExitCode.FatalError)}const corePkg=JSON.parse(await fs.promises.readFile(corePkgPath,"utf-8")),version=corePkg.version;if(!version){await log.error(`${rel(corePkgPath)} has no version field.`);process.exit(ExitCode.FatalError)}await assertNoUncommittedChanges(coreDir,force);const depName=corePkg.name??"stacks",range=`^${await resolvePublishedVersion(depName,version)}`,rootPkgPath=resolve(process.cwd(),"package.json"),rootPkgRaw=await fs.promises.readFile(rootPkgPath,"utf-8"),rootPkg=JSON.parse(rootPkgRaw),provided=new Set([depName,...Object.keys(corePkg.dependencies??{}).filter((name)=>name.startsWith("@stacksjs/"))]);for(const entry of await readdir(coreDir,{withFileTypes:!0}))if(entry.isDirectory())provided.add(`@stacksjs/${entry.name}`);let repointed=0;const repointWorkspaceRanges=(pkg)=>{let touched=!1;for(const field of["dependencies","devDependencies","peerDependencies"]){const deps=pkg[field];if(!deps)continue;for(const[name,spec]of Object.entries(deps)){if(!spec.startsWith("workspace:")||!provided.has(name))continue;deps[name]=range;touched=!0;repointed++}}return touched};repointWorkspaceRanges(rootPkg);if(!rootPkg.dependencies?.[depName]&&!rootPkg.devDependencies?.[depName])rootPkg.dependencies={...rootPkg.dependencies,[depName]:range};let rewrittenScripts=0;for(const[name,script]of Object.entries(rootPkg.scripts??{})){if(!/storage\/framework\/core\/buddy\/src\/cli\.ts/.test(script))continue;rootPkg.scripts[name]=script.replace(/\bbunx?\s+(?:--bun\s+)?\.?\/?storage\/framework\/core\/buddy\/src\/cli\.ts/g,"./buddy");rewrittenScripts++}if(Array.isArray(rootPkg.workspaces)){rootPkg.workspaces=rootPkg.workspaces.filter((glob)=>!isCoreWorkspaceGlob(glob));if(rootPkg.workspaces.length===0)delete rootPkg.workspaces}await fs.promises.writeFile(rootPkgPath,`${JSON.stringify(rootPkg,null,2)}
5
5
  `);for(const glob of rootPkg.workspaces??[])for(const memberPkgPath of globSync(`${glob.replace(/\/$/,"")}/package.json`,{cwd:process.cwd(),absolute:!0})){const raw=await fs.promises.readFile(memberPkgPath,"utf-8"),memberPkg=JSON.parse(raw);if(repointWorkspaceRanges(memberPkg))await fs.promises.writeFile(memberPkgPath,`${JSON.stringify(memberPkg,null,2)}
6
6
  `)}const survivingManifests=await rewriteSurvivingFrameworkManifests(process.cwd(),provided,range),bunfigPath=resolve(process.cwd(),"bunfig.toml");let rewrittenPreloads=0;if(existsSync(bunfigPath)){const bunfig=await fs.promises.readFile(bunfigPath,"utf-8"),{next,packages:preloadedPackages,rewritten}=rewriteBunfigPreloads(bunfig);rewrittenPreloads+=rewritten;if(next!==bunfig)await fs.promises.writeFile(bunfigPath,next);for(const match of next.matchAll(/["'](\.\/[^"']+\.ts)["']/g)){const preloadPath=resolve(process.cwd(),match[1]);if(!existsSync(preloadPath))continue;for(const pkgName of packagesPreloadFilesFallBackTo(await fs.promises.readFile(preloadPath,"utf-8")))preloadedPackages.add(pkgName)}let declaredForPreload=0;for(const pkgName of preloadedPackages){if(rootPkg.dependencies?.[pkgName]||rootPkg.devDependencies?.[pkgName])continue;rootPkg.dependencies={...rootPkg.dependencies,[pkgName]:range};declaredForPreload++}if(declaredForPreload>0)await fs.promises.writeFile(rootPkgPath,`${JSON.stringify(rootPkg,null,2)}
7
7
  `)}const tsconfigPath=resolve(process.cwd(),"tsconfig.json");let rewroteTsconfig=!1,rewroteTypecheck=!1;if(existsSync(tsconfigPath)){const raw=await fs.promises.readFile(tsconfigPath,"utf-8"),next=raw.replace(/"extends"\s*:\s*"\.\/storage\/framework\/core\/tsconfig\.json"/,'"extends": "./storage/framework/tsconfig.app.json"');if(next!==raw){await fs.promises.writeFile(tsconfigPath,next);rewroteTsconfig=!0}}const splitTypecheck=splitFrameworkTypecheckScript(rootPkg.scripts??{});if(splitTypecheck){rootPkg.scripts=splitTypecheck;rewroteTypecheck=!0;await fs.promises.writeFile(rootPkgPath,`${JSON.stringify(rootPkg,null,2)}
8
- `)}const rewrittenCommands=await rewriteCoreCommandPaths(process.cwd()),prunedWorkflows=await pruneVendoredCoreFromWorkflows(process.cwd()),rewrittenImports=await rewriteCoreSourceImports(process.cwd());await fs.promises.rm(coreDir,{recursive:!0,force:!0});const pantryLock=resolve(process.cwd(),"pantry.lock"),removedPantryLock=existsSync(pantryLock);await fs.promises.rm(pantryLock,{force:!0});let danglingRemoved=0;for(const depsDir of["node_modules","pantry"]){const scopedDir=resolve(process.cwd(),depsDir,"@stacksjs");if(!existsSync(scopedDir))continue;for(const entry of await readdir(scopedDir,{withFileTypes:!0})){if(!entry.isSymbolicLink())continue;const link=resolve(scopedDir,entry.name);if(existsSync(link))continue;await fs.promises.rm(link,{force:!0});danglingRemoved++}const rootLink=resolve(process.cwd(),depsDir,depName);if(existsSync(dirname(rootLink))&&isDanglingLink(rootLink)){await fs.promises.rm(rootLink,{force:!0});danglingRemoved++}}log.success(`Removed ${italic(rel(coreDir))}`);log.info(`package.json now depends on ${depName}@${range}`);if(repointed>0)log.info(`Repointed ${repointed} workspace: range${repointed===1?"":"s"} to ${range}`);if(survivingManifests.ranges>0)log.info(`Repointed ${survivingManifests.ranges} workspace: range${survivingManifests.ranges===1?"":"s"} across ${survivingManifests.files.length} surviving framework manifest${survivingManifests.files.length===1?"":"s"}`);if(removedPantryLock)log.info("Removed the legacy Pantry workspace lock; the install will resolve a package-layout graph");if(danglingRemoved>0)log.info(`Removed ${danglingRemoved} node_modules symlink${danglingRemoved===1?"":"s"} left pointing into it`);if(rewrittenScripts>0)log.info(`Repointed ${rewrittenScripts} package.json script${rewrittenScripts===1?"":"s"} to ./buddy`);if(rewrittenPreloads>0)log.info(`Rewrote ${rewrittenPreloads} bunfig.toml preload path${rewrittenPreloads===1?"":"s"} to package specifiers`);if(rewroteTsconfig)log.info("tsconfig.json now extends storage/framework/tsconfig.app.json");if(rewroteTypecheck)log.info("`typecheck` now checks this app as well as the framework files it still ships");for(const pruned of prunedWorkflows){const parts=[pruned.removedJobs.length>0?`${pruned.removedJobs.length} job${pruned.removedJobs.length===1?"":"s"} (${pruned.removedJobs.join(", ")})`:"",pruned.removedSteps>0?`${pruned.removedSteps} step${pruned.removedSteps===1?"":"s"}`:""].filter(Boolean);log.info(`${pruned.file}: removed ${parts.join(" and ")} that ran against the vendored core`)}if(rewrittenCommands.length>0){log.info(`Repointed vendored-CLI commands to ./buddy in ${rewrittenCommands.length} file${rewrittenCommands.length===1?"":"s"}:`);for(const file of rewrittenCommands)log.info(` ${file}`)}if(rewrittenImports.length>0){log.info(`Repointed vendored-source imports to package specifiers in ${rewrittenImports.length} file${rewrittenImports.length===1?"":"s"}:`);for(const file of rewrittenImports)log.info(` ${file}`)}const stragglers=await findCoreReferences(process.cwd());if(stragglers.length>0){log.warn(`${stragglers.length} file${stragglers.length===1?"":"s"} still reference storage/framework/core, which no longer exists:`);for(const{file,line,text}of stragglers)log.warn(` ${file}:${line} ${text}`);log.info("Run those through `./buddy <command>` or a package specifier before deploying.")}const installer=detectInstaller(process.cwd());log.info(`Installing the published packages with \`${installer.join(" ")}\`...`);if(await installWithRetry(()=>Bun.spawn(installer,{cwd:process.cwd(),stdout:"inherit",stderr:"inherit"}).exited,{onRetry:(attempt,delayMs)=>{log.warn(`The install failed. A release published minutes ago can list versions npm cannot serve yet, so retrying in ${Math.round(delayMs/1000)}s (attempt ${attempt} of ${INSTALL_RETRY_DELAYS_MS.length+1})...`)}})!==0){await log.error(`\`${installer.join(" ")}\` failed. package.json and bunfig.toml were updated; re-run the install once the failure is resolved.`);process.exit(ExitCode.FatalError)}log.success("This project now runs on the published Stacks packages.");log.info("Vendor an individual package again any time with `buddy publish:core <pkg>`.")}async function resolvePublishedVersion(depName,vendored){let published;try{published=await fetchPublishedVersions(depName)}catch(error){log.warn(`Could not reach the npm registry to check ${depName} versions (${error instanceof Error?error.message:String(error)}).`);log.info(`Pinning the vendored version, ${depName}@^${vendored}.`);return vendored}if(published.versions.has(vendored))return vendored;if(!published.latest){log.warn(`${depName}@${vendored} is not published and the registry reports no latest version.`);return vendored}log.warn(`${depName}@${vendored} is not published yet - the vendored copy is ahead of npm.`);log.info(`Pinning the newest published version instead, ${depName}@^${published.latest}.`);return published.latest}function normalizeCoreName(pkg){const shortName=pkg.replace(/^@stacksjs\//,"").replace(/^core\//,"");if(!shortName||shortName.includes("/")||shortName.includes("..")){process.stderr.write(`Invalid package name: ${pkg}
8
+ `)}const rewrittenCommands=await rewriteCoreCommandPaths(process.cwd()),prunedWorkflows=await pruneVendoredCoreFromWorkflows(process.cwd()),rewrittenImports=await rewriteCoreSourceImports(process.cwd());await fs.promises.rm(coreDir,{recursive:!0,force:!0});const pantryLock=resolve(process.cwd(),"pantry.lock"),removedPantryLock=existsSync(pantryLock);await fs.promises.rm(pantryLock,{force:!0});let danglingRemoved=0;for(const depsDir of["node_modules","pantry"]){const scopedDir=resolve(process.cwd(),depsDir,"@stacksjs");if(!existsSync(scopedDir))continue;for(const entry of await readdir(scopedDir,{withFileTypes:!0})){if(!entry.isSymbolicLink())continue;const link=resolve(scopedDir,entry.name);if(existsSync(link))continue;await fs.promises.rm(link,{force:!0});danglingRemoved++}const rootLink=resolve(process.cwd(),depsDir,depName);if(existsSync(dirname(rootLink))&&isDanglingLink(rootLink)){await fs.promises.rm(rootLink,{force:!0});danglingRemoved++}}log.success(`Removed ${italic(rel(coreDir))}`);log.info(`package.json now depends on ${depName}@${range}`);if(repointed>0)log.info(`Repointed ${repointed} workspace: range${repointed===1?"":"s"} to ${range}`);if(survivingManifests.ranges>0)log.info(`Repointed ${survivingManifests.ranges} workspace: range${survivingManifests.ranges===1?"":"s"} across ${survivingManifests.files.length} surviving framework manifest${survivingManifests.files.length===1?"":"s"}`);if(removedPantryLock)log.info("Removed the legacy Pantry workspace lock; the install will resolve a package-layout graph");if(danglingRemoved>0)log.info(`Removed ${danglingRemoved} node_modules symlink${danglingRemoved===1?"":"s"} left pointing into it`);if(rewrittenScripts>0)log.info(`Repointed ${rewrittenScripts} package.json script${rewrittenScripts===1?"":"s"} to ./buddy`);if(rewrittenPreloads>0)log.info(`Rewrote ${rewrittenPreloads} bunfig.toml preload path${rewrittenPreloads===1?"":"s"} to package specifiers`);if(rewroteTsconfig)log.info("tsconfig.json now extends storage/framework/tsconfig.app.json");if(rewroteTypecheck)log.info("`typecheck` now checks this app as well as the framework files it still ships");for(const pruned of prunedWorkflows){const parts=[pruned.removedJobs.length>0?`${pruned.removedJobs.length} job${pruned.removedJobs.length===1?"":"s"} (${pruned.removedJobs.join(", ")})`:"",pruned.removedSteps>0?`${pruned.removedSteps} step${pruned.removedSteps===1?"":"s"}`:""].filter(Boolean);log.info(`${pruned.file}: removed ${parts.join(" and ")} that ran against the vendored core`)}if(rewrittenCommands.length>0){log.info(`Repointed vendored-CLI commands to ./buddy in ${rewrittenCommands.length} file${rewrittenCommands.length===1?"":"s"}:`);for(const file of rewrittenCommands)log.info(` ${file}`)}if(rewrittenImports.length>0){log.info(`Repointed vendored-source imports to package specifiers in ${rewrittenImports.length} file${rewrittenImports.length===1?"":"s"}:`);for(const file of rewrittenImports)log.info(` ${file}`)}const stragglers=await findCoreReferences(process.cwd());if(stragglers.length>0){log.warn(`${stragglers.length} file${stragglers.length===1?"":"s"} still reference storage/framework/core, which no longer exists:`);for(const{file,line,text}of stragglers)log.warn(` ${file}:${line} ${text}`);log.info("Run those through `./buddy <command>` or a package specifier before deploying.")}const installer=chooseInstaller(process.cwd(),requestedInstaller);log.info(`Installing the published packages with \`${installer.join(" ")}\`...`);if(await installWithRetry(()=>Bun.spawn(installer,{cwd:process.cwd(),stdout:"inherit",stderr:"inherit"}).exited,{onRetry:(attempt,delayMs)=>{log.warn(`The install failed. A release published minutes ago can list versions npm cannot serve yet, so retrying in ${Math.round(delayMs/1000)}s (attempt ${attempt} of ${INSTALL_RETRY_DELAYS_MS.length+1})...`)}})!==0){await log.error(`\`${installer.join(" ")}\` failed. package.json and bunfig.toml were updated; re-run the install once the failure is resolved.`);process.exit(ExitCode.FatalError)}log.success("This project now runs on the published Stacks packages.");log.info("Vendor an individual package again any time with `buddy publish:core <pkg>`.")}async function resolvePublishedVersion(depName,vendored){let published;try{published=await fetchPublishedVersions(depName)}catch(error){log.warn(`Could not reach the npm registry to check ${depName} versions (${error instanceof Error?error.message:String(error)}).`);log.info(`Pinning the vendored version, ${depName}@^${vendored}.`);return vendored}if(published.versions.has(vendored))return vendored;if(!published.latest){log.warn(`${depName}@${vendored} is not published and the registry reports no latest version.`);return vendored}log.warn(`${depName}@${vendored} is not published yet - the vendored copy is ahead of npm.`);log.info(`Pinning the newest published version instead, ${depName}@^${published.latest}.`);return published.latest}function normalizeCoreName(pkg){const shortName=pkg.replace(/^@stacksjs\//,"").replace(/^core\//,"");if(!shortName||shortName.includes("/")||shortName.includes("..")){process.stderr.write(`Invalid package name: ${pkg}
9
9
  `);process.stderr.write(" Use a short name like `router` or the fully qualified `@stacksjs/router`.\n");process.exit(ExitCode.FatalError)}return shortName}function isCoreWorkspaceGlob(glob){const normalized=glob.replace(/^\.\//,"").replace(/\/$/,"");return normalized==="storage/framework/core"||normalized.startsWith("storage/framework/core/")}async function assertNoUncommittedChanges(dir,force){if(force)return;try{const proc=Bun.spawn(["git","status","--porcelain","--",dir],{cwd:process.cwd(),stdout:"pipe",stderr:"ignore"}),output=await new Response(proc.stdout).text();if(await proc.exited!==0)return;const changed=output.split(`
10
10
  `).filter(Boolean);if(changed.length===0)return;log.error(`${changed.length} uncommitted change${changed.length===1?"":"s"} under ${italic(dir.replace(`${process.cwd()}/`,""))}:`);for(const line of changed.slice(0,10))log.info(` ${line}`);if(changed.length>10)log.info(` ... and ${changed.length-10} more`);log.info("Commit or stash them first, or pass --force to delete them anyway.");await log.flush();process.exit(ExitCode.FatalError)}catch{}}
@@ -1 +1 @@
1
- import process from"node:process";import{runAction}from"@stacksjs/actions";import{intro,log,outro}from"@stacksjs/cli";import{Action}from"@stacksjs/enums";import{ExitCode}from"@stacksjs/types";import{resultFailed}from"../result";export function search(buddy){const descriptions={import:"Indexes database data to search engine",flush:"Flushes all data from search engine",settings:"Update index settings",list:"List index settings",model:"Target a specific model",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("search-engine:update",descriptions.import).option("-m, --model [model]",descriptions.model,{default:""}).option("-f, --flush [flush]",descriptions.flush,{default:!1}).option("-s, --settings [settings]",descriptions.settings,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).action(async(options)=>{log.debug("Running `search-engine:update` ...",options);let actionString=Action.SearchEngineImport,introString="search-engine:update";if(options.model){actionString=Action.SearchEngineImport;introString=`search-engine:update --model ${options.model}`}if(options.settings){actionString=Action.SearchEnginePushSettings;introString="search-engine:update --settings"}if(options.flush){actionString=Action.SearchEngineFlush;introString="search-engine:update --flush"}const perf=await intro(introString),result=await runAction(actionString,options);if(resultFailed(result)){await outro("While running the search-engine:update command, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}await outro("Successfully imported model data to search engine.",{startTime:perf,useSeconds:!0})});buddy.command("search-engine:settings",descriptions.list).option("-m, --model [model]",descriptions.model,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{if(!options.model)log.error("Missing required option --model");log.debug("Running `search-engine:settings` ...",options);const perf=await intro("search-engine:settings"),result=await runAction(Action.SearchEngineListSettings,options);if(resultFailed(result)){await outro("While running the search-engine:settings command, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}await outro("Successfully listed search engine index settings.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("search:reindex [model]","Re-index a model (Scout-style alias for search-engine:update)").option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(model,options)=>{const opts={...options,model:model??""};log.debug("Running `search:reindex` ...",opts);const perf=await intro(`search:reindex${model?` ${model}`:""}`),result=await runAction(Action.SearchEngineImport,opts);if(resultFailed(result)){await outro("While running the search:reindex command, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}await outro(model?`Reindexed ${model}.`:"Reindexed all searchable models.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("search:flush [model]","Delete all documents from a model index (Scout-style alias)").option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(model,options)=>{const opts={...options,model:model??"",flush:!0};log.debug("Running `search:flush` ...",opts);const perf=await intro(`search:flush${model?` ${model}`:""}`),result=await runAction(Action.SearchEngineFlush,opts);if(resultFailed(result)){await outro("While running the search:flush command, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}await outro(model?`Flushed ${model} from search.`:"Flushed all model indices.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)})}
1
+ import process from"node:process";import{runAction}from"@stacksjs/actions";import{intro,log,outro}from"@stacksjs/cli";import{Action}from"@stacksjs/enums";import{ExitCode}from"@stacksjs/types";import{resultFailed}from"../result";export function search(buddy){const descriptions={import:"Indexes database data to search engine",flush:"Flushes all data from search engine",settings:"Update index settings",list:"List index settings",model:"Target a specific model",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("search-engine:update",descriptions.import).option("-m, --model <model>",descriptions.model).option("-f, --flush [flush]",descriptions.flush,{default:!1}).option("-s, --settings [settings]",descriptions.settings,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).action(async(options)=>{log.debug("Running `search-engine:update` ...",options);let actionString=Action.SearchEngineImport,introString="search-engine:update";if(options.model){actionString=Action.SearchEngineImport;introString=`search-engine:update --model ${options.model}`}if(options.settings){actionString=Action.SearchEnginePushSettings;introString="search-engine:update --settings"}if(options.flush){actionString=Action.SearchEngineFlush;introString="search-engine:update --flush"}const perf=await intro(introString),result=await runAction(actionString,options);if(resultFailed(result)){await outro("While running the search-engine:update command, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}await outro("Successfully imported model data to search engine.",{startTime:perf,useSeconds:!0})});buddy.command("search-engine:settings",descriptions.list).option("-m, --model <model>",descriptions.model).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `search-engine:settings` ...",options);const perf=await intro("search-engine:settings"),result=await runAction(Action.SearchEngineListSettings,options);if(resultFailed(result)){await outro("While running the search-engine:settings command, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}await outro("Successfully listed search engine index settings.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("search:reindex [model]","Re-index a model (Scout-style alias for search-engine:update)").option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(model,options)=>{const opts={...options,model:model??""};log.debug("Running `search:reindex` ...",opts);const perf=await intro(`search:reindex${model?` ${model}`:""}`),result=await runAction(Action.SearchEngineImport,opts);if(resultFailed(result)){await outro("While running the search:reindex command, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}await outro(model?`Reindexed ${model}.`:"Reindexed all searchable models.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("search:flush [model]","Delete all documents from a model index (Scout-style alias)").option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(model,options)=>{const opts={...options,model:model??"",flush:!0};log.debug("Running `search:flush` ...",opts);const perf=await intro(`search:flush${model?` ${model}`:""}`),result=await runAction(Action.SearchEngineFlush,opts);if(resultFailed(result)){await outro("While running the search:flush command, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}await outro(model?`Flushed ${model} from search.`:"Flushed all model indices.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)})}
@@ -1,6 +1,14 @@
1
1
  import type { CLI, CliOptions } from '@stacksjs/types';
2
2
  export declare function setup(buddy: CLI): void;
3
3
  export declare function ensurePantryInstalled(): Promise<void>;
4
+ /**
5
+ * `pantry install` in `cwd`, installing Pantry first if it is missing, without
6
+ * exiting. Resolves to why it failed, or `null`.
7
+ *
8
+ * `buddy new` uses this form, because exiting there leaves a half-built tree
9
+ * (stacksjs/stacks#3209). `ensurePantryDependencies` is the exiting form.
10
+ */
11
+ export declare function attemptPantryDependencies(cwd: string): Promise<{ error: unknown } | null>;
4
12
  export declare function ensurePantryDependencies(cwd: string): Promise<void>;
5
13
  export declare function ensureAppKey(cwd: string): Promise<void>;
6
14
  export declare function ensureIdeSettings(cwd: string): void;
@@ -1,4 +1,4 @@
1
- import{cpSync,existsSync,readFileSync,writeFileSync}from"node:fs";import{homedir}from"node:os";import{join}from"node:path";import process from"node:process";import{IosToolchainError,loadIosDependencies,pantryExecutable,pantryInstallArgs,resolveXcodegen,runAction,XCODE_NOTE,xcodeDeveloperDir}from"@stacksjs/actions";import{log,onUnknownSubcommand,runCommand}from"@stacksjs/cli";import{Action}from"@stacksjs/enums";import{handleError}from"@stacksjs/error-handling";import{path as p}from"@stacksjs/path";import{copyFile,storage}from"@stacksjs/storage";import{ExitCode}from"@stacksjs/types";import{setupPrettyDevEnvironment}from"./dev";import{runInitialMigration}from"../initial-migration";import{syncDatabasePortToEnv}from"../pantry-service-ports";import{resolveCreatePolicy}from"../database-preflight";import{resultFailed}from"../result";function getTimeoutMs(envVar,fallbackMs){const value=Number(process.env[envVar]);if(Number.isFinite(value)&&value>0)return value;return fallbackMs}const PANTRY_CHECK_TIMEOUT_MS=getTimeoutMs("PANTRY_CHECK_TIMEOUT_MS",15000),PANTRY_INSTALL_TIMEOUT_MS=getTimeoutMs("PANTRY_INSTALL_TIMEOUT_MS",600000),PANTRY_DEPENDENCIES_TIMEOUT_MS=getTimeoutMs("PANTRY_DEPENDENCIES_TIMEOUT_MS",1200000),KEYGEN_TIMEOUT_MS=getTimeoutMs("KEYGEN_TIMEOUT_MS",120000),AWS_CONFIG_TIMEOUT_MS=getTimeoutMs("AWS_CONFIG_TIMEOUT_MS",900000);export function setup(buddy){const descriptions={setup:"This command ensures your project is setup correctly",ssl:"Setup SSL certificates and hosts file for HTTPS development",ai:"Set the project up for an AI coding agent (Claude Code, Codex, Cursor, Copilot, Gemini)",copy:"Copy the agent files instead of symlinking them, so they can be edited per project",force:"Overwrite files that already exist",ohMyZsh:"Enable Oh My Zsh",aws:"Ensures AWS is connected to the project",project:"Target a specific project",verbose:"Enable verbose output",domain:"Custom domain to setup (defaults to APP_URL)",skipHosts:"Skip adding domain to hosts file",skipTrust:"Skip trusting the certificate",skipAws:"Skip AWS configuration during setup",skipKeygen:"Skip generating an application key during setup",ios:"Install the iOS build tools (`iosDependencies` in config/deps.ts) through Pantry and check for Xcode"};buddy.command("setup",descriptions.setup).alias("ensure").option("-p, --project [project]",descriptions.project,{default:!1}).option("--skip-aws",descriptions.skipAws,{default:!1}).option("--skip-keygen",descriptions.skipKeygen,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy setup` ...",options);await ensurePantryInstalled();await optimizePantryDeps();await initializeProject(options)});buddy.command("setup:ios",descriptions.ios).option("--verbose",descriptions.verbose,{default:!1}).action(async()=>{if(process.platform!=="darwin"){await log.error("The iOS toolchain installs on macOS only: Xcode and xcodegen do not run anywhere else.");process.exit(ExitCode.FatalError)}const root=p.projectPath(),dependencies=await loadIosDependencies(root),pantry=pantryExecutable(root);log.info(`Installing ${Object.entries(dependencies).map(([pkg,version])=>`${pkg}@${version}`).join(", ")} through Pantry`);const install=Bun.spawnSync([pantry,...pantryInstallArgs(dependencies)],{cwd:root,stdin:"inherit",stdout:"inherit",stderr:"inherit"});if(install.exitCode!==0){await log.error(`\`${pantry} install\` failed with exit code ${install.exitCode}. PANTRY_BIN can point at another Pantry.`);process.exit(ExitCode.FatalError)}try{const xcodegen=await resolveXcodegen(root);log.success(`xcodegen ${xcodegen.version}: ${xcodegen.path}`)}catch(error){await log.error(error instanceof IosToolchainError?error.message:String(error));process.exit(ExitCode.FatalError)}const xcode=xcodeDeveloperDir();if(xcode)log.success(`Xcode: ${xcode}`);else log.warn(`No Xcode is selected, so the project can be generated but not built or archived. ${XCODE_NOTE}`)});buddy.command("setup:ssl",descriptions.ssl).alias("ssl:setup").option("-d, --domain [domain]",descriptions.domain).option("--skip-hosts",descriptions.skipHosts,{default:!1}).option("--skip-trust",descriptions.skipTrust,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy setup:ssl` ...",options);if(!await setupPrettyDevEnvironment({domain:options.domain,skipHosts:options.skipHosts,skipTrust:options.skipTrust,verbose:options.verbose})){log.warn("SSL setup completed with warnings");log.info("You may need to manually trust certificates or update hosts file")}});buddy.command("setup:ai [provider]",descriptions.ai).alias("ai:setup").option("--copy",descriptions.copy,{default:!1}).option("--force",descriptions.force,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(provider,options)=>{log.debug("Running `buddy setup:ai` ...",options);const{AI_PROVIDERS,isAiProvider,reportAiSetup,setupAiProvider}=await import("./setup-ai");let id=provider;if(!id){if(!process.stdin.isTTY){await log.error(`\`setup:ai\` needs a provider when stdin is not a terminal. Pass one: ${AI_PROVIDERS.map((entry)=>`buddy setup:ai ${entry.id}`).join(", ")}`);process.exit(ExitCode.InvalidArgument)}const{select}=await import("@stacksjs/cli");id=await select({message:"Which AI coding agent do you use?",choices:AI_PROVIDERS.map((entry)=>({value:entry.id,label:entry.label})),initial:0})}if(!id||!isAiProvider(id)){await log.error(`Unknown AI provider: ${id}. Expected one of: ${AI_PROVIDERS.map((entry)=>entry.id).join(", ")}`);process.exit(ExitCode.InvalidArgument)}const definition=AI_PROVIDERS.find((entry)=>entry.id===id),{generateAutoImportFiles}=await import("@stacksjs/server/imports");await generateAutoImportFiles();reportAiSetup(definition,setupAiProvider(id,{copy:options.copy,force:options.force}))});buddy.command("setup:oh-my-zsh",descriptions.ohMyZsh).alias("upgrade:oh-my-zsh").option("--verbose",descriptions.verbose,{default:!1}).action(async(_options)=>{log.debug("Running `buddy setup:oh-my-zsh` ...",_options);const result=await runAction(Action.UpgradeShell);if(resultFailed(result)){await log.error(result.error);process.exit(ExitCode.FatalError)}});onUnknownSubcommand(buddy,"setup")}async function isPantryInstalled(){try{return(await runCommand("pantry --version",{silent:!0,timeoutMs:PANTRY_CHECK_TIMEOUT_MS})).isOk}catch{return!1}}async function installPantry(){const bundledInstaller=p.frameworkPath("scripts/pantry-install"),command=existsSync(bundledInstaller)?[bundledInstaller]:["sh","-c","curl -fsSL https://pantry.dev | bash"],result=await runCommand(command,{timeoutMs:PANTRY_INSTALL_TIMEOUT_MS}),localBin=join(homedir(),".local","bin");if(!process.env.PATH?.split(":").includes(localBin))process.env.PATH=`${localBin}:${process.env.PATH||""}`;if(result.isOk&&await isPantryInstalled())return;if(resultFailed(result))handleError(result.error);else await log.error("Pantry installed but is not available on PATH. Open a new shell and run `buddy setup` again.");process.exit(ExitCode.FatalError)}export async function ensurePantryInstalled(){if(await isPantryInstalled())return;log.info("Pantry is required. Installing it from https://pantry.dev...");await installPantry()}export async function ensurePantryDependencies(cwd){await ensurePantryInstalled();log.info("Installing project dependencies with Pantry...");const result=await runCommand("pantry install",{cwd,timeoutMs:PANTRY_DEPENDENCIES_TIMEOUT_MS});if(resultFailed(result)){handleError(result.error);process.exit(ExitCode.FatalError)}if(existsSync(join(cwd,"package.json"))&&!existsSync(join(cwd,"node_modules"))){await log.error("Pantry completed without installing the project JavaScript dependencies.");process.exit(ExitCode.FatalError)}log.success("Installed project dependencies with Pantry")}function hasAppKey(cwd){const envPath=join(cwd,".env");if(!existsSync(envPath))return!1;return/^APP_KEY=.+$/m.test(readFileSync(envPath,"utf-8"))}export async function ensureAppKey(cwd){if(hasAppKey(cwd)||process.env.APP_KEY&&process.env.APP_KEY.length>0){log.success("APP_KEY existed");return}const keyResult=await runCommand("./buddy key:generate",{cwd,timeoutMs:KEYGEN_TIMEOUT_MS});if(resultFailed(keyResult)){handleError(keyResult.error);process.exit(ExitCode.FatalError)}log.success("Generated application key")}async function databaseIsReachable(){try{const{describeTarget,probeTargetDatabase,resolveConnectionTarget}=await import("@stacksjs/database"),target=resolveConnectionTarget();if(!target)return{ok:!0};const probe=await probeTargetDatabase(target);if(probe.ok)return{ok:!0};if(probe.kind==="missing-database"&&resolveCreatePolicy()!=="never"){process.env.STACKS_CREATE_DATABASE="1";return{ok:!0}}return{ok:!1,reason:`${describeTarget(target)} is not reachable yet (${probe.kind})`}}catch{return{ok:!0}}}async function initializeProject(options){const cwd=options.cwd||p.projectPath();await ensurePantryDependencies(cwd);await ensureEnvIsSet(options);const portSync=syncDatabasePortToEnv(cwd);if(portSync.port!==void 0)process.env.DB_PORT=String(portSync.port);if(portSync.changed)log.info(`Pointed DB_PORT at ${portSync.port}, the port Pantry assigned this project's ${portSync.service} service`);if(!options.skipKeygen)await ensureAppKey(cwd);const migration=await runInitialMigration({appEnv:process.env.APP_ENV||process.env.NODE_ENV||"local",isReachable:databaseIsReachable,migrate:()=>runAction(Action.Migrate,{cwd}),failed:resultFailed,log});ensureIdeSettings(cwd);if(!options.skipAws){log.info("Ensuring AWS is connected...");try{const awsResult=await runCommand("./buddy configure:aws",{cwd,timeoutMs:AWS_CONFIG_TIMEOUT_MS});if(resultFailed(awsResult)){log.warn("AWS not configured - you can do this later via ./buddy configure:aws");log.debug(awsResult.error)}else log.success("Configured AWS")}catch(error){log.warn("AWS not configured - you can do this later via ./buddy configure:aws");log.debug(error)}}if(migration==="failed"){process.stderr.write(`
1
+ import{cpSync,existsSync,readFileSync,writeFileSync}from"node:fs";import{homedir}from"node:os";import{join}from"node:path";import process from"node:process";import{IosToolchainError,loadIosDependencies,pantryExecutable,pantryInstallArgs,resolveXcodegen,runAction,XCODE_NOTE,xcodeDeveloperDir}from"@stacksjs/actions";import{log,onUnknownSubcommand,runCommand}from"@stacksjs/cli";import{Action}from"@stacksjs/enums";import{handleError}from"@stacksjs/error-handling";import{path as p}from"@stacksjs/path";import{copyFile,storage}from"@stacksjs/storage";import{ExitCode}from"@stacksjs/types";import{setupPrettyDevEnvironment}from"./dev";import{runInitialMigration}from"../initial-migration";import{syncDatabasePortToEnv}from"../pantry-service-ports";import{resolveCreatePolicy}from"../database-preflight";import{resultFailed}from"../result";function getTimeoutMs(envVar,fallbackMs){const value=Number(process.env[envVar]);if(Number.isFinite(value)&&value>0)return value;return fallbackMs}const PANTRY_CHECK_TIMEOUT_MS=getTimeoutMs("PANTRY_CHECK_TIMEOUT_MS",15000),PANTRY_INSTALL_TIMEOUT_MS=getTimeoutMs("PANTRY_INSTALL_TIMEOUT_MS",600000),PANTRY_DEPENDENCIES_TIMEOUT_MS=getTimeoutMs("PANTRY_DEPENDENCIES_TIMEOUT_MS",1200000),KEYGEN_TIMEOUT_MS=getTimeoutMs("KEYGEN_TIMEOUT_MS",120000),AWS_CONFIG_TIMEOUT_MS=getTimeoutMs("AWS_CONFIG_TIMEOUT_MS",900000);export function setup(buddy){const descriptions={setup:"This command ensures your project is setup correctly",ssl:"Setup SSL certificates and hosts file for HTTPS development",ai:"Set the project up for an AI coding agent (Claude Code, Codex, Cursor, Copilot, Gemini)",copy:"Copy the agent files instead of symlinking them, so they can be edited per project",force:"Overwrite files that already exist",ohMyZsh:"Enable Oh My Zsh",aws:"Ensures AWS is connected to the project",project:"Target a specific project",verbose:"Enable verbose output",domain:"Custom domain to setup (defaults to APP_URL)",skipHosts:"Skip adding domain to hosts file",skipTrust:"Skip trusting the certificate",skipAws:"Skip AWS configuration during setup",skipKeygen:"Skip generating an application key during setup",ios:"Install the iOS build tools (`iosDependencies` in config/deps.ts) through Pantry and check for Xcode"};buddy.command("setup",descriptions.setup).alias("ensure").option("-p, --project [project]",descriptions.project,{default:!1}).option("--skip-aws",descriptions.skipAws,{default:!1}).option("--skip-keygen",descriptions.skipKeygen,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy setup` ...",options);await ensurePantryInstalled();await optimizePantryDeps();await initializeProject(options)});buddy.command("setup:ios",descriptions.ios).option("--verbose",descriptions.verbose,{default:!1}).action(async()=>{if(process.platform!=="darwin"){await log.error("The iOS toolchain installs on macOS only: Xcode and xcodegen do not run anywhere else.");process.exit(ExitCode.FatalError)}const root=p.projectPath(),dependencies=await loadIosDependencies(root),pantry=pantryExecutable(root);log.info(`Installing ${Object.entries(dependencies).map(([pkg,version])=>`${pkg}@${version}`).join(", ")} through Pantry`);const install=Bun.spawnSync([pantry,...pantryInstallArgs(dependencies)],{cwd:root,stdin:"inherit",stdout:"inherit",stderr:"inherit"});if(install.exitCode!==0){await log.error(`\`${pantry} install\` failed with exit code ${install.exitCode}. PANTRY_BIN can point at another Pantry.`);process.exit(ExitCode.FatalError)}try{const xcodegen=await resolveXcodegen(root);log.success(`xcodegen ${xcodegen.version}: ${xcodegen.path}`)}catch(error){await log.error(error instanceof IosToolchainError?error.message:String(error));process.exit(ExitCode.FatalError)}const xcode=xcodeDeveloperDir();if(xcode)log.success(`Xcode: ${xcode}`);else log.warn(`No Xcode is selected, so the project can be generated but not built or archived. ${XCODE_NOTE}`)});buddy.command("setup:ssl",descriptions.ssl).alias("ssl:setup").option("-d, --domain [domain]",descriptions.domain).option("--skip-hosts",descriptions.skipHosts,{default:!1}).option("--skip-trust",descriptions.skipTrust,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy setup:ssl` ...",options);if(!await setupPrettyDevEnvironment({domain:options.domain,skipHosts:options.skipHosts,skipTrust:options.skipTrust,verbose:options.verbose})){log.warn("SSL setup completed with warnings");log.info("You may need to manually trust certificates or update hosts file")}});buddy.command("setup:ai [provider]",descriptions.ai).alias("ai:setup").option("--copy",descriptions.copy,{default:!1}).option("--force",descriptions.force,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(provider,options)=>{log.debug("Running `buddy setup:ai` ...",options);const{AI_PROVIDERS,isAiProvider,reportAiSetup,setupAiProvider}=await import("./setup-ai");let id=provider;if(!id){if(!process.stdin.isTTY){await log.error(`\`setup:ai\` needs a provider when stdin is not a terminal. Pass one: ${AI_PROVIDERS.map((entry)=>`buddy setup:ai ${entry.id}`).join(", ")}`);process.exit(ExitCode.InvalidArgument)}const{select}=await import("@stacksjs/cli");id=await select({message:"Which AI coding agent do you use?",choices:AI_PROVIDERS.map((entry)=>({value:entry.id,label:entry.label})),initial:0})}if(!id||!isAiProvider(id)){await log.error(`Unknown AI provider: ${id}. Expected one of: ${AI_PROVIDERS.map((entry)=>entry.id).join(", ")}`);process.exit(ExitCode.InvalidArgument)}const definition=AI_PROVIDERS.find((entry)=>entry.id===id),{generateAutoImportFiles}=await import("@stacksjs/server/imports");await generateAutoImportFiles();reportAiSetup(definition,setupAiProvider(id,{copy:options.copy,force:options.force}))});buddy.command("setup:oh-my-zsh",descriptions.ohMyZsh).alias("upgrade:oh-my-zsh").option("--verbose",descriptions.verbose,{default:!1}).action(async(_options)=>{log.debug("Running `buddy setup:oh-my-zsh` ...",_options);const result=await runAction(Action.UpgradeShell);if(resultFailed(result)){await log.error(result.error);process.exit(ExitCode.FatalError)}});onUnknownSubcommand(buddy,"setup")}async function isPantryInstalled(){try{return(await runCommand("pantry --version",{silent:!0,timeoutMs:PANTRY_CHECK_TIMEOUT_MS})).isOk}catch{return!1}}const PANTRY_NOT_ON_PATH="Pantry installed but is not available on PATH. Open a new shell and run `buddy setup` again.";async function attemptPantryInstall(){const bundledInstaller=p.frameworkPath("scripts/pantry-install"),command=existsSync(bundledInstaller)?[bundledInstaller]:["sh","-c","curl -fsSL https://pantry.dev | bash"],result=await runCommand(command,{timeoutMs:PANTRY_INSTALL_TIMEOUT_MS}),localBin=join(homedir(),".local","bin");if(!process.env.PATH?.split(":").includes(localBin))process.env.PATH=`${localBin}:${process.env.PATH||""}`;if(result.isOk&&await isPantryInstalled())return null;return{error:resultFailed(result)?result.error:Error(PANTRY_NOT_ON_PATH)}}async function reportPantryFailure(error){if(error instanceof Error&&error.message===PANTRY_NOT_ON_PATH)await log.error(PANTRY_NOT_ON_PATH);else handleError(error)}async function installPantry(){const failure=await attemptPantryInstall();if(failure===null)return;await reportPantryFailure(failure.error);process.exit(ExitCode.FatalError)}export async function ensurePantryInstalled(){if(await isPantryInstalled())return;log.info("Pantry is required. Installing it from https://pantry.dev...");await installPantry()}export async function attemptPantryDependencies(cwd){if(!await isPantryInstalled()){log.info("Pantry is required. Installing it from https://pantry.dev...");const installFailure=await attemptPantryInstall();if(installFailure!==null)return installFailure}log.info("Installing project dependencies with Pantry...");const result=await runCommand("pantry install",{cwd,timeoutMs:PANTRY_DEPENDENCIES_TIMEOUT_MS});return resultFailed(result)?{error:result.error}:null}export async function ensurePantryDependencies(cwd){const failure=await attemptPantryDependencies(cwd);if(failure!==null){await reportPantryFailure(failure.error);process.exit(ExitCode.FatalError)}if(existsSync(join(cwd,"package.json"))&&!existsSync(join(cwd,"node_modules"))){await log.error("Pantry completed without installing the project JavaScript dependencies.");process.exit(ExitCode.FatalError)}log.success("Installed project dependencies with Pantry")}function hasAppKey(cwd){const envPath=join(cwd,".env");if(!existsSync(envPath))return!1;return/^APP_KEY=.+$/m.test(readFileSync(envPath,"utf-8"))}export async function ensureAppKey(cwd){if(hasAppKey(cwd)||process.env.APP_KEY&&process.env.APP_KEY.length>0){log.success("APP_KEY existed");return}const keyResult=await runCommand("./buddy key:generate",{cwd,timeoutMs:KEYGEN_TIMEOUT_MS});if(resultFailed(keyResult)){handleError(keyResult.error);process.exit(ExitCode.FatalError)}log.success("Generated application key")}async function databaseIsReachable(){try{const{describeTarget,probeTargetDatabase,resolveConnectionTarget}=await import("@stacksjs/database"),target=resolveConnectionTarget();if(!target)return{ok:!0};const probe=await probeTargetDatabase(target);if(probe.ok)return{ok:!0};if(probe.kind==="missing-database"&&resolveCreatePolicy()!=="never"){process.env.STACKS_CREATE_DATABASE="1";return{ok:!0}}return{ok:!1,reason:`${describeTarget(target)} is not reachable yet (${probe.kind})`}}catch{return{ok:!0}}}async function initializeProject(options){const cwd=options.cwd||p.projectPath();await ensurePantryDependencies(cwd);await ensureEnvIsSet(options);const portSync=syncDatabasePortToEnv(cwd);if(portSync.port!==void 0)process.env.DB_PORT=String(portSync.port);if(portSync.changed)log.info(`Pointed DB_PORT at ${portSync.port}, the port Pantry assigned this project's ${portSync.service} service`);if(!options.skipKeygen)await ensureAppKey(cwd);const migration=await runInitialMigration({appEnv:process.env.APP_ENV||process.env.NODE_ENV||"local",isReachable:databaseIsReachable,migrate:()=>runAction(Action.Migrate,{cwd}),failed:resultFailed,log});ensureIdeSettings(cwd);if(!options.skipAws){log.info("Ensuring AWS is connected...");try{const awsResult=await runCommand("./buddy configure:aws",{cwd,timeoutMs:AWS_CONFIG_TIMEOUT_MS});if(resultFailed(awsResult)){log.warn("AWS not configured - you can do this later via ./buddy configure:aws");log.debug(awsResult.error)}else log.success("Configured AWS")}catch(error){log.warn("AWS not configured - you can do this later via ./buddy configure:aws");log.debug(error)}}if(migration==="failed"){process.stderr.write(`
2
2
  Initial database migration FAILED, so this project is not set up.
3
3
  `);process.stderr.write(`Its database did not receive the schema; the error is above.
4
4
  `);process.stderr.write("Fix the migration, then run `./buddy migrate`.\n");await log.flush();process.exit(ExitCode.FatalError)}log.success("Project is setup");log.info("Run `./buddy doctor` anytime to check your setup. Happy coding! \uD83D\uDC99")}export function ensureIdeSettings(cwd){const source=p.frameworkPath("defaults/ide/vscode/.vscode"),destination=join(cwd,".vscode");if(existsSync(destination)){log.debug(".vscode already exists; keeping the project settings");return}if(!existsSync(source)){log.debug("No bundled VS Code settings found; skipping IDE setup");return}cpSync(source,destination,{recursive:!0});log.success("Installed project VS Code settings")}const DB_CONNECTION_PACKAGES={postgres:{name:"postgresql.org",version:"^17.10",service:"postgres"},mysql:{name:"mysql.com",version:"^9.2",service:"mysql"},sqlite:{name:"sqlite.org",version:"^3.47.2"}};function databaseAliases(connection,pkg){return[connection,pkg.name]}export function pantryDatabasePackage(connection){return DB_CONNECTION_PACKAGES[connection]}function detectDbPackage(cwd){const envPath=join(cwd,".env"),envExamplePath=join(cwd,".env.example"),filePath=existsSync(envPath)?envPath:existsSync(envExamplePath)?envExamplePath:void 0;if(!filePath)return;const match=readFileSync(filePath,"utf-8").match(/^DB_CONNECTION=(.+)$/m);if(!match)return;const value=match[1].trim().replace(/['"]/g,"");return pantryDatabasePackage(value)}export async function optimizePantryDeps(cwd=p.projectPath()){const depsConfigPath=join(cwd,"config","deps.ts");if(!existsSync(depsConfigPath)){log.debug("No config/deps.ts found, skipping dependency optimization");return!1}let configDeps={},configServices=[],configDefined={};try{const mod=await import(depsConfigPath),config=mod.config||mod.default;if(config?.dependencies)configDeps={...config.dependencies};if(Array.isArray(config?.services?.autoStart))configServices=config.services.autoStart.filter((name)=>typeof name==="string");if(config?.services?.define&&typeof config.services.define==="object")configDefined=config.services.define}catch(err){log.debug("Could not load config/deps.ts, skipping dependency optimization");return!1}const dbPackage=detectDbPackage(cwd),autoStart=[...configServices];if(dbPackage){const selected=new Set(Object.entries(DB_CONNECTION_PACKAGES).filter(([,pkg])=>pkg.name===dbPackage.name).flatMap(([connection,pkg])=>databaseAliases(connection,pkg))),unused=new Set(Object.entries(DB_CONNECTION_PACKAGES).flatMap(([connection,pkg])=>databaseAliases(connection,pkg)).filter((alias)=>!selected.has(alias)));for(const pkg of Object.keys(configDeps)){const domain=pkg.split("/")[0];if(unused.has(domain)){log.info(`DB_CONNECTION selects ${dbPackage.name}, dropping unused ${pkg}`);delete configDeps[pkg]}}if(!Object.keys(configDeps).some((key)=>{const domain=key.split("/")[0];return selected.has(domain)})){log.info(`Detected DB_CONNECTION requires ${dbPackage.name}, adding to dependencies`);configDeps[dbPackage.name]=dbPackage.version}if(dbPackage.service&&!autoStart.includes(dbPackage.service))autoStart.push(dbPackage.service)}const lines=["# Auto-generated from config/deps.ts and .env sniffing.","# This file is regenerated on each `buddy setup` run.","#","# To learn more, please visit:","# https://stacksjs.com/docs/dependency-management","","dependencies:"];for(const[pkg,version]of Object.entries(configDeps))lines.push(` ${pkg}: ${version}`);const defined=Object.entries(configDefined);if(autoStart.length>0||defined.length>0){lines.push("","services:"," enabled: true");if(autoStart.length>0){lines.push(" autoStart:");for(const service of autoStart)lines.push(` - ${service}`)}if(defined.length>0){lines.push(" define:");for(const[name,definition]of defined){if(!definition||typeof definition!=="object")continue;lines.push(` ${name}:`);for(const[key,value]of Object.entries(definition)){if(value===void 0||value===null)continue;lines.push(` ${key}: ${String(value)}`)}}}}const depsYamlPath=join(cwd,"deps.yaml");writeFileSync(depsYamlPath,`${lines.join(`
@@ -1 +1 @@
1
- import{existsSync}from"node:fs";import{join}from"node:path";import process from"node:process";import{enterRequestScope,installRequestScope}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{siteConfigPath}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{resolveStxSource}from"@stacksjs/actions";import{serverRequestBodyOptions}from"@stacksjs/server/request-body";installRequestScope();export function resolveUserPartialsPath(cwd=process.cwd(),configuredDir){if(configuredDir){const configured=[join(cwd,"resources",configuredDir),join(cwd,configuredDir)].find((candidate)=>existsSync(candidate));if(configured)return configured}const existing=["resources/partials","resources/views/partials","partials","resources/components"].filter((candidate)=>existsSync(join(cwd,candidate)));if(existing.length===0)return;const populated=existing.find((candidate)=>containsTemplates(join(cwd,candidate)));return join(cwd,populated??existing[0])}function containsTemplates(dir){try{return[...new Bun.Glob("**/*.stx").scanSync({cwd:dir,onlyFiles:!0})].length>0}catch{return!1}}export async function loadStxPartialsDir(cwd=process.cwd()){for(const name of["stx","ui"]){const configPath=join(cwd,`config/${name}.ts`);if(!existsSync(configPath))continue;try{const dir=(await import(configPath)).default?.partialsDir;if(typeof dir==="string"&&dir.length>0)return dir}catch{}}return}function resolveCsrfMiddlewarePath(){const rel="app/Middleware/Csrf.ts",vendored=join(process.cwd(),"storage/framework/defaults",rel);if(existsSync(vendored))return vendored;try{const pkgJson=Bun.resolveSync("@stacksjs/defaults/package.json",process.cwd());return`${pkgJson.slice(0,pkgJson.lastIndexOf("/"))}/${rel}`}catch{return vendored}}export async function startProductionServer(options){if(options?.port)process.env.PORT=String(options.port);process.env.APP_ENV=process.env.APP_ENV||"production";const port=Number(process.env.PORT)||3000,{config,feature,overridesReady,resolveViewPatterns}=await import("@stacksjs/config");await overridesReady;const{ensureDiscoveredPackages}=await import("@stacksjs/actions");await ensureDiscoveredPackages();const{applyResponseHeaders,applyViewSecurityHeaders,describeApiProxyRules,describeRedirectRules,describeRewriteRules,injectGlobalAutoImports,loadRouteRedirects,resolveApiBase,resolveApiProxyRules,resolveEmbeddableRules,resolveRedirectRules,resolveRewriteRules,viewClientAddress}=await import("@stacksjs/server"),{resolveDefaultsResources}=await import("@stacksjs/actions/dev/defaults-resources"),{stxPageAuthMiddleware}=await import("@stacksjs/auth"),{enhanceRequest,loadMiddlewareHandlers,registerPeerSource}=await import("@stacksjs/router"),pageMiddleware=await loadMiddlewareHandlers();try{const{autoImportsAreStale,generateAutoImportFiles}=await import("@stacksjs/server");if(autoImportsAreStale()){log.info("[server] Installed packages moved since the auto-import barrel was written; rebuilding it.");await generateAutoImportFiles({declarations:!1})}}catch(error){log.warn(`[server] Could not refresh the auto-import barrel: ${error instanceof Error?error.message:String(error)}`)}await injectGlobalAutoImports();let stxServe;const serveSource=resolveStxSource({value:process.env.BUN_PLUGIN_STX_SRC});if(serveSource.kind==="missing")await log.exit(`BUN_PLUGIN_STX_SRC points at ${serveSource.path}, which does not exist. Unset it to use the installed bun-plugin-stx.`,ExitCode.FatalError);if(serveSource.kind==="override"){({serve:stxServe}=await import(serveSource.path));log.warn(`Serving views through ${serveSource.path} instead of the installed bun-plugin-stx.`)}else({serve:stxServe}=await import("bun-plugin-stx/serve"));log.debug(`stx serve implementation: ${serveSource.kind==="override"?serveSource.path:"bun-plugin-stx/serve"}`);const stxModule=await resolveVendoredStxModule(),{site:siteConfig,i18n:i18nConfig}=await loadStxSiteConfig(),userViewsPath="resources/views",defaultsResources=resolveDefaultsResources(),defaultViewsPath=join(defaultsResources,"views"),userLayoutsPath=existsSync("resources/views/layouts")?"resources/views/layouts":"resources/layouts",userComponentsPath=existsSync("resources/views/components")?"resources/views/components":"resources/components",userPartialsPath=resolveUserPartialsPath(process.cwd(),await loadStxPartialsDir()),apiBase=resolveApiBase(config.ports?.api),{mountedDefaultRouteBundles}=await import("@stacksjs/router"),viewPatterns=resolveViewPatterns(userViewsPath,defaultViewsPath,config?.ui?.defaultViews,void 0,void 0,mountedDefaultRouteBundles(feature));for(const name of viewPatterns.missing)log.warn(`ui.defaultViews lists "${name}", which does not exist under ${defaultViewsPath} - ignoring.`);if(viewPatterns.withheld.length>0)log.info(`Default views without a mounted route bundle behind them, not served: ${viewPatterns.withheld.join(", ")}`);const apiProxyRules=resolveApiProxyRules(config.server?.proxy);if(apiProxyRules.paths.length>0||apiProxyRules.prefixes.length>1)log.info(`API proxy: ${describeApiProxyRules(apiProxyRules)}`);const redirectRules=resolveRedirectRules({...await loadRouteRedirects(),...config.server?.redirects});if(redirectRules.size>0)log.info(`Redirects: ${describeRedirectRules(redirectRules)}`);const rewriteRules=resolveRewriteRules(config.server?.rewrites);if(rewriteRules.size>0)log.info(`Rewrites: ${describeRewriteRules(rewriteRules)}`);const{createSiteSeoHandler,describeSeoAtBoot}=await import("@stacksjs/actions/seo"),seoOptions={root:process.cwd(),seo:config.app?.seo,appUrl:config.app?.url},siteSeo=createSiteSeoHandler({...seoOptions,cacheTtlMs:600000});for(const note of await describeSeoAtBoot(seoOptions).catch(()=>[]))log.warn(note);const cacheConfig=config.server?.cache,documentCacheControl=buildDocumentCacheControl(cacheConfig?.documents);if(cacheConfig?.renders)log.info(`Render cache: on, keyed by ${cacheConfig.renderVary??"request"}${cacheConfig.prewarm?", prewarmed":""}`);if(documentCacheControl)log.info(`Document cache: ${documentCacheControl}`);const embeddableRules=resolveEmbeddableRules(config.server?.security?.embeddable);if(embeddableRules.paths.length>0||embeddableRules.prefixes.length>0)log.info(`Frameable by other origins: ${[...embeddableRules.paths,...embeddableRules.prefixes].join(" ")}`);log.info(`Starting production server on port ${port}...`);await stxServe({...serverRequestBodyOptions(config.server?.maxRequestBodySize),patterns:viewPatterns.patterns,exclude:viewPatterns.exclude,port,autoIncrementPort:!1,reusePort:["production","staging","development"].includes((process.env.APP_ENV||"").toLowerCase()),componentsDir:userComponentsPath,fallbackComponentsDir:join(defaultsResources,"components"),layoutsDir:userLayoutsPath,...userPartialsPath&&{partialsDir:userPartialsPath},fallbackLayoutsDir:join(defaultsResources,"layouts"),fallbackPartialsDir:defaultViewsPath,quiet:options?.verbose!==!0,...cacheConfig?.renders&&{renderCache:!0,renderCacheVary:cacheConfig.renderVary??"request",...cacheConfig.prewarm&&{prewarmRenderCache:!0}},...stxModule&&{stxModule},...i18nConfig&&{i18n:i18nConfig},...siteConfig?.url&&{site:siteConfig},...config.server?.domains&&{domains:config.server.domains},middleware:{...pageMiddleware,...stxPageAuthMiddleware()},prepareMiddlewareRequest:(request)=>enhanceRequest(request),clientAddress:viewClientAddress,onRequest:async(req,server)=>{const snapshot=enterRequestScope(req);registerPeerSource(server);const{maintenanceGate,isApiBoundRequest:isApiBound,proxyToBackend,resolveRedirect,resolveRewrite}=await import("@stacksjs/server"),gated=await maintenanceGate(req);if(gated)return gated;const url=new URL(req.url),redirected=resolveRedirect(url,redirectRules);if(redirected)return redirected;const rewritten=resolveRewrite(url.pathname,rewriteRules);if(rewritten){if(!apiBase){log.error(`No API target configured for ${url.pathname} (rewritten to ${rewritten}); refusing to proxy.`);return new Response("Bad Gateway",{status:502})}try{const target=new URL(`${rewritten}${url.search}`,url.origin);return await proxyToBackend(new Request(target,req),apiBase,void 0,req)}catch(error){log.error(`Rewrite of ${url.pathname} to ${rewritten} failed: ${error.message}`);return new Response("Bad Gateway",{status:502})}}const seoFile=await siteSeo(req);if(seoFile)return seoFile;if(isApiBound(req,url.pathname,apiProxyRules)){if(!apiBase){log.error(`No API target configured for ${url.pathname}. This app shares its host with other deployments, so there is no safe default port to guess - refusing to proxy. Set PORT_API (or API_URL) for this site, and deploy an \`api\` site on its own port.`);return new Response("Bad Gateway",{status:502})}try{return await proxyToBackend(req,apiBase)}catch(error){log.error(`API proxy to ${apiBase} failed: ${error.message}`);return new Response("Bad Gateway",{status:502})}}if(existsSync(join(process.cwd(),"resources/views/blog.stx"))){const{renderBlogFeed}=await import("@stacksjs/actions/blog"),feed=await renderBlogFeed(req);if(feed)return feed}if(config.analytics?.capturePageviews)import("@stacksjs/analytics").then(({recordPageview})=>recordPageview(req)).catch(()=>{});if(config.sites?.enabled){const sites=await import("@stacksjs/sites"),resolved=await sites.resolveSiteByHost(sites.requestHost(req.headers,sites.sitesOptions()));sites.setCurrentSite(resolved);snapshot.site=sites.toSiteSnapshot(resolved)}return},onResponse:async(req,response)=>{const securityResponse=applyViewSecurityHeaders(req,response,embeddableRules),secured=applyResponseHeaders(req,securityResponse??response,config.server?.headers)??securityResponse,method=req.method.toUpperCase();if(method!=="GET"&&method!=="HEAD")return secured;const baseline=secured??response;let current=baseline;if(current.status===404&&config.sites?.enabled)try{const{cmsNotFoundFallback}=await import("@stacksjs/cms"),cmsResponse=await cmsNotFoundFallback(req);if(cmsResponse)current=cmsResponse}catch(error){log.debug(`CMS fallback skipped: ${error.message}`)}let finished;try{const{seedCsrfCookieIfMissing}=await import(resolveCsrfMiddlewarePath());finished=await seedCsrfCookieIfMissing(req,current)??(current===baseline?secured:current)}catch(error){log.debug(`CSRF cookie seeding skipped: ${error.message}`);finished=current===baseline?secured:current}if(!documentCacheControl)return finished;return applyDocumentCacheControl(req,finished??response,documentCacheControl)}});log.success(`Production server listening on http://0.0.0.0:${port}`)}export function buildDocumentCacheControl(documents){if(!documents)return;const maxAge=Number(documents.maxAge??0);if(!Number.isFinite(maxAge)||maxAge<=0)return;const stale=Number(documents.staleWhileRevalidate??0),parts=["public",`max-age=${Math.floor(maxAge)}`];if(Number.isFinite(stale)&&stale>0)parts.push(`stale-while-revalidate=${Math.floor(stale)}`);return parts.join(", ")}export function isAuthenticatedRequest(request){if(request.headers.get("authorization"))return!0;const cookie=request.headers.get("cookie")||"";if(!cookie)return!1;return cookie.split(";").map((part)=>part.trim().split("=")[0]?.toLowerCase()??"").some((name)=>name!==""&&!name.includes("csrf")&&/session|auth|token|remember/.test(name))}const SPA_NAV_REQUEST_HEADER="X-STX-Router",SPA_NAV_FRAGMENT_HEADER="X-STX-Fragment";export function isSpaFragmentExchange(request,response){return request.headers.get(SPA_NAV_REQUEST_HEADER)==="true"||response.headers.get(SPA_NAV_FRAGMENT_HEADER)==="true"}export function applyDocumentCacheControl(request,response,cacheControl){if(!cacheControl)return response;const contentType=response.headers.get("content-type")||"";if(response.status!==200||!contentType.startsWith("text/html"))return response;if(isSpaFragmentExchange(request,response))return response;if(response.headers.getSetCookie().length>0)return response;if(isAuthenticatedRequest(request))return response;const headers=new Headers(response.headers);headers.set("cache-control",cacheControl);return new Response(response.body,{status:response.status,statusText:response.statusText,headers})}async function resolveVendoredStxModule(){const source=resolveStxSource({value:process.env.STACKS_STX_SRC});if(source.kind==="missing")await log.exit(`STACKS_STX_SRC points at ${source.path}, which does not exist. Unset it to use the installed @stacksjs/stx.`,ExitCode.FatalError);if(source.kind==="override"){log.warn(`Rendering through ${source.path} instead of the installed @stacksjs/stx.`);return await import(source.path)}try{return await import("@stacksjs/stx")}catch{}return}function fallbackI18nFromSite(site){const locales=site.i18n.locales,defaultLocale=site.i18n.defaultLocale??locales[0];return{locales,defaultLocale,labels:site.i18n.labels??Object.fromEntries(locales.map((c)=>[c,c.toUpperCase()])),translations:{},pickerSelector:site.i18n.pickerSelector??"#lang-picker"}}async function resolveSiteI18n(site){try{const resolved=await resolveVendoredStxModule();if(typeof resolved?.resolveI18n==="function"){const i18n=resolved.resolveI18n(site,process.cwd());if(i18n)return i18n}}catch{}return fallbackI18nFromSite(site)}async function loadStxSiteConfig(){const sitePath=siteConfigPath();if(!existsSync(sitePath))return{};try{const mod=await import(sitePath),site=mod.default??mod.site??mod.config;if(!site)return{};if(!site.i18n)return{site};const i18n=await resolveSiteI18n(site);return{site,i18n}}catch{}return{}}
1
+ import{existsSync}from"node:fs";import{join}from"node:path";import process from"node:process";import{enterRequestScope,installRequestScope}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{siteConfigPath}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{resolveStxSource}from"@stacksjs/actions";import{serverRequestBodyOptions}from"@stacksjs/server/request-body";import{beginRequestCapture,finishRequestCapture}from"@stacksjs/router/request-capture";installRequestScope();export function resolveUserPartialsPath(cwd=process.cwd(),configuredDir){if(configuredDir){const configured=[join(cwd,"resources",configuredDir),join(cwd,configuredDir)].find((candidate)=>existsSync(candidate));if(configured)return configured}const existing=["resources/partials","resources/views/partials","partials","resources/components"].filter((candidate)=>existsSync(join(cwd,candidate)));if(existing.length===0)return;const populated=existing.find((candidate)=>containsTemplates(join(cwd,candidate)));return join(cwd,populated??existing[0])}function containsTemplates(dir){try{return[...new Bun.Glob("**/*.stx").scanSync({cwd:dir,onlyFiles:!0})].length>0}catch{return!1}}export async function loadStxPartialsDir(cwd=process.cwd()){for(const name of["stx","ui"]){const configPath=join(cwd,`config/${name}.ts`);if(!existsSync(configPath))continue;try{const dir=(await import(configPath)).default?.partialsDir;if(typeof dir==="string"&&dir.length>0)return dir}catch{}}return}function resolveCsrfMiddlewarePath(){const rel="app/Middleware/Csrf.ts",vendored=join(process.cwd(),"storage/framework/defaults",rel);if(existsSync(vendored))return vendored;try{const pkgJson=Bun.resolveSync("@stacksjs/defaults/package.json",process.cwd());return`${pkgJson.slice(0,pkgJson.lastIndexOf("/"))}/${rel}`}catch{return vendored}}export async function startProductionServer(options){if(options?.port)process.env.PORT=String(options.port);process.env.APP_ENV=process.env.APP_ENV||"production";const port=Number(process.env.PORT)||3000,{config,feature,overridesReady,resolveViewPatterns}=await import("@stacksjs/config");await overridesReady;const{ensureDiscoveredPackages}=await import("@stacksjs/actions");await ensureDiscoveredPackages();const{applyResponseHeaders,applyViewSecurityHeaders,describeApiProxyRules,describeRedirectRules,describeRewriteRules,injectGlobalAutoImports,loadRouteRedirects,resolveApiBase,resolveApiProxyRules,resolveEmbeddableRules,resolveRedirectRules,resolveRewriteRules,viewClientAddress}=await import("@stacksjs/server"),{resolveDefaultsResources}=await import("@stacksjs/actions/dev/defaults-resources"),{stxPageAuthMiddleware}=await import("@stacksjs/auth"),{enhanceRequest,loadMiddlewareHandlers,registerPeerSource}=await import("@stacksjs/router"),pageMiddleware=await loadMiddlewareHandlers();try{const{autoImportsAreStale,generateAutoImportFiles}=await import("@stacksjs/server");if(autoImportsAreStale()){log.info("[server] Installed packages moved since the auto-import barrel was written; rebuilding it.");await generateAutoImportFiles({declarations:!1})}}catch(error){log.warn(`[server] Could not refresh the auto-import barrel: ${error instanceof Error?error.message:String(error)}`)}await injectGlobalAutoImports();let stxServe;const serveSource=resolveStxSource({value:process.env.BUN_PLUGIN_STX_SRC});if(serveSource.kind==="missing")await log.exit(`BUN_PLUGIN_STX_SRC points at ${serveSource.path}, which does not exist. Unset it to use the installed bun-plugin-stx.`,ExitCode.FatalError);if(serveSource.kind==="override"){({serve:stxServe}=await import(serveSource.path));log.warn(`Serving views through ${serveSource.path} instead of the installed bun-plugin-stx.`)}else({serve:stxServe}=await import("bun-plugin-stx/serve"));log.debug(`stx serve implementation: ${serveSource.kind==="override"?serveSource.path:"bun-plugin-stx/serve"}`);const stxModule=await resolveVendoredStxModule(),{site:siteConfig,i18n:i18nConfig}=await loadStxSiteConfig(),userViewsPath="resources/views",defaultsResources=resolveDefaultsResources(),defaultViewsPath=join(defaultsResources,"views"),userLayoutsPath=existsSync("resources/views/layouts")?"resources/views/layouts":"resources/layouts",userComponentsPath=existsSync("resources/views/components")?"resources/views/components":"resources/components",userPartialsPath=resolveUserPartialsPath(process.cwd(),await loadStxPartialsDir()),apiBase=resolveApiBase(config.ports?.api),{mountedDefaultRouteBundles}=await import("@stacksjs/router"),viewPatterns=resolveViewPatterns(userViewsPath,defaultViewsPath,config?.ui?.defaultViews,void 0,void 0,mountedDefaultRouteBundles(feature));for(const name of viewPatterns.missing)log.warn(`ui.defaultViews lists "${name}", which does not exist under ${defaultViewsPath} - ignoring.`);if(viewPatterns.withheld.length>0)log.info(`Default views without a mounted route bundle behind them, not served: ${viewPatterns.withheld.join(", ")}`);const apiProxyRules=resolveApiProxyRules(config.server?.proxy);if(apiProxyRules.paths.length>0||apiProxyRules.prefixes.length>1)log.info(`API proxy: ${describeApiProxyRules(apiProxyRules)}`);const redirectRules=resolveRedirectRules({...await loadRouteRedirects(),...config.server?.redirects});if(redirectRules.size>0)log.info(`Redirects: ${describeRedirectRules(redirectRules)}`);const rewriteRules=resolveRewriteRules(config.server?.rewrites);if(rewriteRules.size>0)log.info(`Rewrites: ${describeRewriteRules(rewriteRules)}`);const{createSiteSeoHandler,describeSeoAtBoot}=await import("@stacksjs/actions/seo"),seoOptions={root:process.cwd(),seo:config.app?.seo,appUrl:config.app?.url},siteSeo=createSiteSeoHandler({...seoOptions,cacheTtlMs:600000});for(const note of await describeSeoAtBoot(seoOptions).catch(()=>[]))log.warn(note);const cacheConfig=config.server?.cache,documentCacheControl=buildDocumentCacheControl(cacheConfig?.documents);if(cacheConfig?.renders)log.info(`Render cache: on, keyed by ${cacheConfig.renderVary??"request"}${cacheConfig.prewarm?", prewarmed":""}`);if(documentCacheControl)log.info(`Document cache: ${documentCacheControl}`);const embeddableRules=resolveEmbeddableRules(config.server?.security?.embeddable);if(embeddableRules.paths.length>0||embeddableRules.prefixes.length>0)log.info(`Frameable by other origins: ${[...embeddableRules.paths,...embeddableRules.prefixes].join(" ")}`);log.info(`Starting production server on port ${port}...`);await stxServe({...serverRequestBodyOptions(config.server?.maxRequestBodySize),patterns:viewPatterns.patterns,exclude:viewPatterns.exclude,port,autoIncrementPort:!1,reusePort:["production","staging","development"].includes((process.env.APP_ENV||"").toLowerCase()),componentsDir:userComponentsPath,fallbackComponentsDir:join(defaultsResources,"components"),layoutsDir:userLayoutsPath,...userPartialsPath&&{partialsDir:userPartialsPath},fallbackLayoutsDir:join(defaultsResources,"layouts"),fallbackPartialsDir:defaultViewsPath,quiet:options?.verbose!==!0,...cacheConfig?.renders&&{renderCache:!0,renderCacheVary:cacheConfig.renderVary??"request",...cacheConfig.prewarm&&{prewarmRenderCache:!0}},...stxModule&&{stxModule},...i18nConfig&&{i18n:i18nConfig},...siteConfig?.url&&{site:siteConfig},...config.server?.domains&&{domains:config.server.domains},middleware:{...pageMiddleware,...stxPageAuthMiddleware()},prepareMiddlewareRequest:(request)=>enhanceRequest(request),clientAddress:viewClientAddress,onRequest:async(req,server)=>{beginRequestCapture(req);const snapshot=enterRequestScope(req);registerPeerSource(server);const{maintenanceGate,isApiBoundRequest:isApiBound,proxyToBackend,resolveRedirect,resolveRewrite}=await import("@stacksjs/server"),gated=await maintenanceGate(req);if(gated)return gated;const url=new URL(req.url),redirected=resolveRedirect(url,redirectRules);if(redirected)return redirected;const rewritten=resolveRewrite(url.pathname,rewriteRules);if(rewritten){if(!apiBase){log.error(`No API target configured for ${url.pathname} (rewritten to ${rewritten}); refusing to proxy.`);return new Response("Bad Gateway",{status:502})}try{const target=new URL(`${rewritten}${url.search}`,url.origin);return await proxyToBackend(new Request(target,req),apiBase,void 0,req)}catch(error){log.error(`Rewrite of ${url.pathname} to ${rewritten} failed: ${error.message}`);return new Response("Bad Gateway",{status:502})}}const seoFile=await siteSeo(req);if(seoFile)return seoFile;if(isApiBound(req,url.pathname,apiProxyRules)){if(!apiBase){log.error(`No API target configured for ${url.pathname}. This app shares its host with other deployments, so there is no safe default port to guess - refusing to proxy. Set PORT_API (or API_URL) for this site, and deploy an \`api\` site on its own port.`);return new Response("Bad Gateway",{status:502})}try{return await proxyToBackend(req,apiBase)}catch(error){log.error(`API proxy to ${apiBase} failed: ${error.message}`);return new Response("Bad Gateway",{status:502})}}if(existsSync(join(process.cwd(),"resources/views/blog.stx"))){const{renderBlogFeed}=await import("@stacksjs/actions/blog"),feed=await renderBlogFeed(req);if(feed)return feed}if(config.analytics?.capturePageviews)import("@stacksjs/analytics").then(({recordPageview})=>recordPageview(req)).catch(()=>{});if(config.sites?.enabled){const sites=await import("@stacksjs/sites"),resolved=await sites.resolveSiteByHost(sites.requestHost(req.headers,sites.sitesOptions()));sites.setCurrentSite(resolved);snapshot.site=sites.toSiteSnapshot(resolved)}return},onResponse:async(req,response)=>{const securityResponse=applyViewSecurityHeaders(req,response,embeddableRules),secured=applyResponseHeaders(req,securityResponse??response,config.server?.headers)??securityResponse,method=req.method.toUpperCase();if(method!=="GET"&&method!=="HEAD"){finishRequestCapture(req,secured??response);return secured}const baseline=secured??response;let current=baseline;if(current.status===404&&config.sites?.enabled)try{const{cmsNotFoundFallback}=await import("@stacksjs/cms"),cmsResponse=await cmsNotFoundFallback(req);if(cmsResponse)current=cmsResponse}catch(error){log.debug(`CMS fallback skipped: ${error.message}`)}let finished;try{const{seedCsrfCookieIfMissing}=await import(resolveCsrfMiddlewarePath());finished=await seedCsrfCookieIfMissing(req,current)??(current===baseline?secured:current)}catch(error){log.debug(`CSRF cookie seeding skipped: ${error.message}`);finished=current===baseline?secured:current}if(!documentCacheControl){finishRequestCapture(req,finished??response);return finished}const cached=applyDocumentCacheControl(req,finished??response,documentCacheControl);finishRequestCapture(req,cached??finished??response);return cached}});log.success(`Production server listening on http://0.0.0.0:${port}`)}export function buildDocumentCacheControl(documents){if(!documents)return;const maxAge=Number(documents.maxAge??0);if(!Number.isFinite(maxAge)||maxAge<=0)return;const stale=Number(documents.staleWhileRevalidate??0),parts=["public",`max-age=${Math.floor(maxAge)}`];if(Number.isFinite(stale)&&stale>0)parts.push(`stale-while-revalidate=${Math.floor(stale)}`);return parts.join(", ")}export function isAuthenticatedRequest(request){if(request.headers.get("authorization"))return!0;const cookie=request.headers.get("cookie")||"";if(!cookie)return!1;return cookie.split(";").map((part)=>part.trim().split("=")[0]?.toLowerCase()??"").some((name)=>name!==""&&!name.includes("csrf")&&/session|auth|token|remember/.test(name))}const SPA_NAV_REQUEST_HEADER="X-STX-Router",SPA_NAV_FRAGMENT_HEADER="X-STX-Fragment";export function isSpaFragmentExchange(request,response){return request.headers.get(SPA_NAV_REQUEST_HEADER)==="true"||response.headers.get(SPA_NAV_FRAGMENT_HEADER)==="true"}export function applyDocumentCacheControl(request,response,cacheControl){if(!cacheControl)return response;const contentType=response.headers.get("content-type")||"";if(response.status!==200||!contentType.startsWith("text/html"))return response;if(isSpaFragmentExchange(request,response))return response;if(response.headers.getSetCookie().length>0)return response;if(isAuthenticatedRequest(request))return response;const headers=new Headers(response.headers);headers.set("cache-control",cacheControl);return new Response(response.body,{status:response.status,statusText:response.statusText,headers})}async function resolveVendoredStxModule(){const source=resolveStxSource({value:process.env.STACKS_STX_SRC});if(source.kind==="missing")await log.exit(`STACKS_STX_SRC points at ${source.path}, which does not exist. Unset it to use the installed @stacksjs/stx.`,ExitCode.FatalError);if(source.kind==="override"){log.warn(`Rendering through ${source.path} instead of the installed @stacksjs/stx.`);return await import(source.path)}try{return await import("@stacksjs/stx")}catch{}return}function fallbackI18nFromSite(site){const locales=site.i18n.locales,defaultLocale=site.i18n.defaultLocale??locales[0];return{locales,defaultLocale,labels:site.i18n.labels??Object.fromEntries(locales.map((c)=>[c,c.toUpperCase()])),translations:{},pickerSelector:site.i18n.pickerSelector??"#lang-picker"}}async function resolveSiteI18n(site){try{const resolved=await resolveVendoredStxModule();if(typeof resolved?.resolveI18n==="function"){const i18n=resolved.resolveI18n(site,process.cwd());if(i18n)return i18n}}catch{}return fallbackI18nFromSite(site)}async function loadStxSiteConfig(){const sitePath=siteConfigPath();if(!existsSync(sitePath))return{};try{const mod=await import(sitePath),site=mod.default??mod.site??mod.config;if(!site)return{};if(!site.i18n)return{site};const i18n=await resolveSiteI18n(site);return{site,i18n}}catch{}return{}}
@@ -0,0 +1,38 @@
1
+ export declare function installScaffoldDependencies(run: ScaffoldDependencyRunners): Promise<ScaffoldDependencyOutcome>;
2
+ /**
3
+ * The Bun to run `bun install` with: the one on PATH, else the Bun running this
4
+ * process. Not the running process when buddy is a compiled binary, where
5
+ * `process.execPath` is buddy itself and `<buddy> install` would run buddy's own
6
+ * `install` command. `null` when there is no Bun to use.
7
+ */
8
+ export declare function bunExecutable(onPath: string | null, execPath: string, compiled: boolean): string | null;
9
+ /** One line for a failure value an installer produced. */
10
+ export declare function failureReason(error: unknown): string;
11
+ /**
12
+ * Installing a new app's dependencies, for `buddy new`.
13
+ *
14
+ * `pantry install` does two jobs in a scaffold: it installs the system
15
+ * dependencies `deps.yaml` declares (bun, sqlite, git, ...) from the Pantry
16
+ * registry, and it installs the app's JavaScript packages. Only the second is
17
+ * needed to finish the scaffold: every later step runs the app's own
18
+ * `./buddy`, which needs `node_modules`, and none of them needs a system
19
+ * package Pantry would have added.
20
+ *
21
+ * A Pantry failure used to end `buddy new` on the spot, with the template's
22
+ * vendored framework still in place and no `node_modules`: a directory that
23
+ * was neither the template nor an app (stacksjs/stacks#3209, seen while the
24
+ * Pantry registry was unreachable). Now the JavaScript packages are installed
25
+ * with the Bun running `buddy new`, the scaffold finishes, and the caller
26
+ * reports the step that is left. The failure is reported, not hidden: the
27
+ * caller still exits non-zero.
28
+ */
29
+ export declare interface ScaffoldDependencyRunners {
30
+ pantry: () => Promise<string | null>
31
+ hasNodeModules: () => boolean
32
+ bunInstall: () => Promise<string | null>
33
+ }
34
+ export type ScaffoldDependencyOutcome = | { status: 'complete' }
35
+ /** The scaffold can finish; the system dependencies still need `pantry install`. */
36
+ | { status: 'system-dependencies-missing', pantryFailure: string }
37
+ /** The scaffold cannot finish: neither installer produced `node_modules`. */
38
+ | { status: 'failed', pantryFailure: string | null, bunFailure: string }
@@ -0,0 +1 @@
1
+ export async function installScaffoldDependencies(run){const pantryFailure=await run.pantry();if(pantryFailure===null&&run.hasNodeModules())return{status:"complete"};const bunFailure=await run.bunInstall();if(bunFailure!==null)return{status:"failed",pantryFailure,bunFailure};if(!run.hasNodeModules())return{status:"failed",pantryFailure,bunFailure:"`bun install` finished without creating node_modules."};if(pantryFailure===null)return{status:"complete"};return{status:"system-dependencies-missing",pantryFailure}}export function bunExecutable(onPath,execPath,compiled){if(onPath)return onPath;return compiled?null:execPath}export function failureReason(error){if(error instanceof Error)return error.message;return String(error)}
@@ -6,6 +6,18 @@
6
6
  */
7
7
  export declare function isDanglingLink(target: string): boolean;
8
8
  export declare function detectInstaller(cwd: string): string[];
9
+ export declare function isUnvendorInstaller(value: unknown): value is UnvendorInstaller;
10
+ /**
11
+ * The install command for the unvendored project: the one asked for, or the
12
+ * one `detectInstaller` picks.
13
+ *
14
+ * `buddy new` asks for Bun when `pantry install` already failed on the app's
15
+ * system dependencies (stacksjs/stacks#3209). The failed attempt leaves a
16
+ * `pantry/` directory, so detection would pick Pantry again, and the retries
17
+ * below would spend eight minutes re-running an install that cannot reach its
18
+ * registry, when all this step needs is the JavaScript packages.
19
+ */
20
+ export declare function chooseInstaller(cwd: string, requested?: UnvendorInstaller): string[];
9
21
  /**
10
22
  * Run an install, retrying a failure after each of `delaysMs`.
11
23
  *
@@ -29,6 +41,8 @@ export declare function rewriteSurvivingFrameworkManifests(cwd: string, provided
29
41
  export declare function rewriteCoreCommandPaths(cwd: string): Promise<string[]>;
30
42
  export declare function rewriteCoreSourceImports(cwd: string): Promise<string[]>;
31
43
  export declare function findCoreReferences(cwd: string): Promise<{ file: string, line: number, text: string }[]>;
44
+ /** The installers `buddy unpublish:core --installer` accepts. */
45
+ export declare const UNVENDOR_INSTALLERS: readonly ['bun', 'pantry'];
32
46
  /**
33
47
  * How long to keep retrying an install that failed, between attempts.
34
48
  *
@@ -45,3 +59,4 @@ export declare function findCoreReferences(cwd: string): Promise<{ file: string,
45
59
  * @defaultValue `[15_000, 30_000, 60_000, 90_000, 120_000, 180_000]`
46
60
  */
47
61
  export declare const INSTALL_RETRY_DELAYS_MS: unknown[];
62
+ export type UnvendorInstaller = typeof UNVENDOR_INSTALLERS[number];
@@ -1,3 +1,3 @@
1
- import{existsSync,lstatSync,readFileSync}from"node:fs";import{readdir}from"node:fs/promises";import{join,resolve}from"node:path";import{log}from"@stacksjs/cli";import{fs}from"@stacksjs/storage";export function isDanglingLink(target){try{return lstatSync(target).isSymbolicLink()&&!existsSync(target)}catch{return!1}}function hoistedLinker(cwd){try{const bunfig=readFileSync(resolve(cwd,"bunfig.toml"),"utf-8");return/^\s*linker\s*=\s*["']hoisted["']/m.test(bunfig)}catch{return!1}}export function detectInstaller(cwd){const has=(rel)=>existsSync(resolve(cwd,rel)),usesPantry=has("pantry")||has("pantry.lock")&&!has("node_modules");if(usesPantry&&Bun.which("pantry")){if(hoistedLinker(cwd))return["pantry","install","--linker","hoisted"];return["pantry","install"]}if(usesPantry)log.warn("This project installs with pantry, but no `pantry` binary is on PATH \u2014 falling back to `bun install`.");return["bun","install"]}export const INSTALL_RETRY_DELAYS_MS=[15000,30000,60000,90000,120000,180000];export async function installWithRetry(run,options={}){const delays=options.delaysMs??INSTALL_RETRY_DELAYS_MS,sleep=options.sleep??((ms)=>Bun.sleep(ms));let code=await run();for(const[i,delay]of delays.entries()){if(code===0)break;options.onRetry?.(i+2,delay);await sleep(delay);code=await run()}return code}export async function rewriteSurvivingFrameworkManifests(cwd,provided,range){const framework=resolve(cwd,"storage/framework"),files=[];let ranges=0;const walk=async(dir)=>{let entries;try{entries=await readdir(dir,{withFileTypes:!0})}catch{return}for(const entry of entries){if(entry.name==="core"||entry.name==="node_modules"||entry.name==="dist")continue;const full=join(dir,entry.name);if(entry.isDirectory()){await walk(full);continue}if(!entry.isFile()||entry.name!=="package.json")continue;const raw=await fs.promises.readFile(full,"utf-8"),pkg=JSON.parse(raw);let touched=!1;for(const field of["dependencies","devDependencies","peerDependencies"]){const dependencies=pkg[field];if(!dependencies)continue;for(const[name,spec]of Object.entries(dependencies)){if(!spec.startsWith("workspace:")||!provided.has(name))continue;dependencies[name]=range;ranges++;touched=!0}}if(!touched)continue;await fs.promises.writeFile(full,`${JSON.stringify(pkg,null,2)}
1
+ import{existsSync,lstatSync,readFileSync}from"node:fs";import{readdir}from"node:fs/promises";import{join,resolve}from"node:path";import{log}from"@stacksjs/cli";import{fs}from"@stacksjs/storage";export function isDanglingLink(target){try{return lstatSync(target).isSymbolicLink()&&!existsSync(target)}catch{return!1}}function hoistedLinker(cwd){try{const bunfig=readFileSync(resolve(cwd,"bunfig.toml"),"utf-8");return/^\s*linker\s*=\s*["']hoisted["']/m.test(bunfig)}catch{return!1}}export function detectInstaller(cwd){const has=(rel)=>existsSync(resolve(cwd,rel)),usesPantry=has("pantry")||has("pantry.lock")&&!has("node_modules");if(usesPantry&&Bun.which("pantry")){if(hoistedLinker(cwd))return["pantry","install","--linker","hoisted"];return["pantry","install"]}if(usesPantry)log.warn("This project installs with pantry, but no `pantry` binary is on PATH \u2014 falling back to `bun install`.");return["bun","install"]}export const UNVENDOR_INSTALLERS=["bun","pantry"];export function isUnvendorInstaller(value){return typeof value==="string"&&UNVENDOR_INSTALLERS.includes(value)}export function chooseInstaller(cwd,requested){if(requested==="bun")return["bun","install"];if(requested==="pantry")return hoistedLinker(cwd)?["pantry","install","--linker","hoisted"]:["pantry","install"];return detectInstaller(cwd)}export const INSTALL_RETRY_DELAYS_MS=[15000,30000,60000,90000,120000,180000];export async function installWithRetry(run,options={}){const delays=options.delaysMs??INSTALL_RETRY_DELAYS_MS,sleep=options.sleep??((ms)=>Bun.sleep(ms));let code=await run();for(const[i,delay]of delays.entries()){if(code===0)break;options.onRetry?.(i+2,delay);await sleep(delay);code=await run()}return code}export async function rewriteSurvivingFrameworkManifests(cwd,provided,range){const framework=resolve(cwd,"storage/framework"),files=[];let ranges=0;const walk=async(dir)=>{let entries;try{entries=await readdir(dir,{withFileTypes:!0})}catch{return}for(const entry of entries){if(entry.name==="core"||entry.name==="node_modules"||entry.name==="dist")continue;const full=join(dir,entry.name);if(entry.isDirectory()){await walk(full);continue}if(!entry.isFile()||entry.name!=="package.json")continue;const raw=await fs.promises.readFile(full,"utf-8"),pkg=JSON.parse(raw);let touched=!1;for(const field of["dependencies","devDependencies","peerDependencies"]){const dependencies=pkg[field];if(!dependencies)continue;for(const[name,spec]of Object.entries(dependencies)){if(!spec.startsWith("workspace:")||!provided.has(name))continue;dependencies[name]=range;ranges++;touched=!0}}if(!touched)continue;await fs.promises.writeFile(full,`${JSON.stringify(pkg,null,2)}
2
2
  `);files.push(full.replace(`${cwd}/`,""))}};await walk(framework);return{files,ranges}}const SCANNED_EXTENSIONS=new Set([".ts",".tsx",".js",".mjs",".cjs",".json",".sh",".yml",".yaml",".toml"]),SKIPPED_DIRECTORIES=new Set(["node_modules","pantry","dist","storage","public","coverage","temp","tmp",".git",".cache",".claude",".idea",".stx",".vscode"]);async function*projectFiles(cwd){const walk=async function*(dir){let entries;try{entries=await readdir(dir,{withFileTypes:!0})}catch{return}for(const entry of entries){const full=join(dir,entry.name);if(entry.isDirectory()){if(SKIPPED_DIRECTORIES.has(entry.name))continue;yield*walk(full);continue}if(!entry.isFile())continue;const dot=entry.name.lastIndexOf("."),ext=dot===-1?"":entry.name.slice(dot);if(SCANNED_EXTENSIONS.has(ext)||entry.name==="Dockerfile"||entry.name.startsWith("Dockerfile."))yield full}};yield*walk(cwd)}const CORE_SOURCE_IMPORT=/(\bfrom\s+|\bimport\s*\(\s*|\brequire\s*\(\s*)(['"])(?:\.{1,2}\/)*storage\/framework\/core\/([\w.-]+)\/src\/([^'"]+?)(?:\.ts)?\2/g;function toPackageSpecifier(pkg,rest){const subpath=rest.replace(/\/index$/,"");return subpath==="index"?`@stacksjs/${pkg}`:`@stacksjs/${pkg}/${subpath}`}const CORE_ACTION_COMMANDS={"actions/src/migrate/database":"migrate","actions/src/migrate/fresh":"migrate:fresh","actions/src/database/seed":"seed","actions/src/auth/setup":"auth:setup","actions/src/dev/api":"dev:api","actions/src/key-generate":"key:generate"},CORE_COMMAND_PATH=/\bbunx?\s+(?:-{1,2}[\w=.-]+\s+)*(?:\.\/)?storage\/framework\/core\/([\w/.-]+?)\.ts\b/g;export async function rewriteCoreCommandPaths(cwd){const touched=[];for await(const file of projectFiles(cwd)){const raw=await fs.promises.readFile(file,"utf-8");if(!raw.includes("storage/framework/core/"))continue;const next=raw.replace(CORE_COMMAND_PATH,(match,entry)=>{if(entry==="buddy/src/cli")return"./buddy";const command=CORE_ACTION_COMMANDS[entry];return command?`./buddy ${command}`:match});if(next!==raw){await fs.promises.writeFile(file,next);touched.push(file.replace(`${cwd}/`,""))}}return touched}export async function rewriteCoreSourceImports(cwd){const touched=[];for await(const file of projectFiles(cwd)){const raw=await fs.promises.readFile(file,"utf-8");if(!raw.includes("storage/framework/core/"))continue;const next=raw.replace(CORE_SOURCE_IMPORT,(_match,lead,quote,pkg,rest)=>`${lead}${quote}${toPackageSpecifier(pkg,rest)}${quote}`);if(next!==raw){await fs.promises.writeFile(file,next);touched.push(file.replace(`${cwd}/`,""))}}return touched}export async function findCoreReferences(cwd){const hits=[];for await(const file of projectFiles(cwd)){const raw=await fs.promises.readFile(file,"utf-8");if(!raw.includes("storage/framework/core"))continue;raw.split(`
3
3
  `).forEach((text,index)=>{if(!text.includes("storage/framework/core"))return;const trimmed=text.trim();if(/^(?:\/\/|\*|#|<!--)/.test(trimmed))return;hits.push({file:file.replace(`${cwd}/`,""),line:index+1,text:trimmed.slice(0,120)})})}return hits}
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.489",
5
+ "version": "0.75.492",
6
6
  "description": "Meet Buddy. The Stacks runtime.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -95,69 +95,69 @@
95
95
  "prepublishOnly": "bun run build"
96
96
  },
97
97
  "dependencies": {
98
- "@stacksjs/actions": "0.75.489",
99
- "@stacksjs/ai": "0.75.489",
100
- "@stacksjs/alias": "0.75.489",
101
- "@stacksjs/analytics": "0.75.489",
102
- "@stacksjs/api": "0.75.489",
103
- "@stacksjs/arrays": "0.75.489",
104
- "@stacksjs/auth": "0.75.489",
105
- "@stacksjs/browser-extension": "0.75.489",
106
- "@stacksjs/build": "0.75.489",
98
+ "@stacksjs/actions": "0.75.492",
99
+ "@stacksjs/ai": "0.75.492",
100
+ "@stacksjs/alias": "0.75.492",
101
+ "@stacksjs/analytics": "0.75.492",
102
+ "@stacksjs/api": "0.75.492",
103
+ "@stacksjs/arrays": "0.75.492",
104
+ "@stacksjs/auth": "0.75.492",
105
+ "@stacksjs/browser-extension": "0.75.492",
106
+ "@stacksjs/build": "0.75.492",
107
107
  "@stacksjs/bumpx": "^0.2.26",
108
- "@stacksjs/cache": "0.75.489",
109
- "@stacksjs/chat": "0.75.489",
108
+ "@stacksjs/cache": "0.75.492",
109
+ "@stacksjs/chat": "0.75.492",
110
110
  "@stacksjs/clapp": "^0.2.16",
111
- "@stacksjs/cli": "0.75.489",
112
- "@stacksjs/cloud": "0.75.489",
113
- "@stacksjs/cms": "0.75.489",
114
- "@stacksjs/collections": "0.75.489",
115
- "@stacksjs/commerce": "0.75.489",
116
- "@stacksjs/config": "0.75.489",
117
- "@stacksjs/database": "0.75.489",
118
- "@stacksjs/desktop-build": "0.75.489",
119
- "@stacksjs/dns": "0.75.489",
111
+ "@stacksjs/cli": "0.75.492",
112
+ "@stacksjs/cloud": "0.75.492",
113
+ "@stacksjs/cms": "0.75.492",
114
+ "@stacksjs/collections": "0.75.492",
115
+ "@stacksjs/commerce": "0.75.492",
116
+ "@stacksjs/config": "0.75.492",
117
+ "@stacksjs/database": "0.75.492",
118
+ "@stacksjs/desktop-build": "0.75.492",
119
+ "@stacksjs/dns": "0.75.492",
120
120
  "@stacksjs/dnsx": "^0.2.3",
121
- "@stacksjs/email": "0.75.489",
122
- "@stacksjs/enums": "0.75.489",
123
- "@stacksjs/env": "0.75.489",
124
- "@stacksjs/error-handling": "0.75.489",
125
- "@stacksjs/events": "0.75.489",
126
- "@stacksjs/features": "0.75.489",
127
- "@stacksjs/git": "0.75.489",
121
+ "@stacksjs/email": "0.75.492",
122
+ "@stacksjs/enums": "0.75.492",
123
+ "@stacksjs/env": "0.75.492",
124
+ "@stacksjs/error-handling": "0.75.492",
125
+ "@stacksjs/events": "0.75.492",
126
+ "@stacksjs/features": "0.75.492",
127
+ "@stacksjs/git": "0.75.492",
128
128
  "@stacksjs/gitit": "^0.2.5",
129
- "@stacksjs/health": "0.75.489",
129
+ "@stacksjs/health": "0.75.492",
130
130
  "@stacksjs/httx": "^0.1.10",
131
- "@stacksjs/image": "0.75.489",
132
- "@stacksjs/lint": "0.75.489",
133
- "@stacksjs/logging": "0.75.489",
134
- "@stacksjs/notifications": "0.75.489",
135
- "@stacksjs/objects": "0.75.489",
136
- "@stacksjs/orm": "0.75.489",
137
- "@stacksjs/path": "0.75.489",
138
- "@stacksjs/payments": "0.75.489",
139
- "@stacksjs/realtime": "0.75.489",
140
- "@stacksjs/router": "0.75.489",
131
+ "@stacksjs/image": "0.75.492",
132
+ "@stacksjs/lint": "0.75.492",
133
+ "@stacksjs/logging": "0.75.492",
134
+ "@stacksjs/notifications": "0.75.492",
135
+ "@stacksjs/objects": "0.75.492",
136
+ "@stacksjs/orm": "0.75.492",
137
+ "@stacksjs/path": "0.75.492",
138
+ "@stacksjs/payments": "0.75.492",
139
+ "@stacksjs/realtime": "0.75.492",
140
+ "@stacksjs/router": "0.75.492",
141
141
  "@stacksjs/rpx": "^0.11.54",
142
- "@stacksjs/scheduler": "0.75.489",
143
- "@stacksjs/search-engine": "0.75.489",
144
- "@stacksjs/security": "0.75.489",
145
- "@stacksjs/server": "0.75.489",
146
- "@stacksjs/sites": "0.75.489",
147
- "@stacksjs/skills": "0.75.489",
148
- "@stacksjs/socials": "0.75.489",
149
- "@stacksjs/storage": "0.75.489",
150
- "@stacksjs/strings": "0.75.489",
142
+ "@stacksjs/scheduler": "0.75.492",
143
+ "@stacksjs/search-engine": "0.75.492",
144
+ "@stacksjs/security": "0.75.492",
145
+ "@stacksjs/server": "0.75.492",
146
+ "@stacksjs/sites": "0.75.492",
147
+ "@stacksjs/skills": "0.75.492",
148
+ "@stacksjs/socials": "0.75.492",
149
+ "@stacksjs/storage": "0.75.492",
150
+ "@stacksjs/strings": "0.75.492",
151
151
  "@stacksjs/stx": "0.2.807",
152
- "@stacksjs/testing": "0.75.489",
153
- "@stacksjs/tinker": "0.75.489",
152
+ "@stacksjs/testing": "0.75.492",
153
+ "@stacksjs/tinker": "0.75.492",
154
154
  "@stacksjs/tlsx": "^0.13.19",
155
155
  "@stacksjs/ts-cloud": "^0.16.92",
156
- "@stacksjs/tunnel": "0.75.489",
157
- "@stacksjs/types": "0.75.489",
158
- "@stacksjs/ui": "0.75.489",
159
- "@stacksjs/utils": "0.75.489",
160
- "@stacksjs/validation": "0.75.489",
156
+ "@stacksjs/tunnel": "0.75.492",
157
+ "@stacksjs/types": "0.75.492",
158
+ "@stacksjs/ui": "0.75.492",
159
+ "@stacksjs/utils": "0.75.492",
160
+ "@stacksjs/validation": "0.75.492",
161
161
  "ajv": "^8.20.0",
162
162
  "ajv-formats": "^3.0.1",
163
163
  "bun-plugin-stx": "0.2.807",